Upload
joie
View
27
Download
0
Embed Size (px)
DESCRIPTION
The Java Language and Environment. Cecilia Bastarrica, Anupama Vadali, and Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-255 Storrs, CT 06269-2155. [email protected] http://www.engr.uconn.edu/~steve - PowerPoint PPT Presentation
Citation preview
CSE333
Java-1.1
The Java Language and EnvironmentThe Java Language and Environment
Cecilia Bastarrica, Anupama Vadali, andProf. Steven A. Demurjian, Sr.
Computer Science & Engineering DepartmentThe University of Connecticut371 Fairfield Road, Box U-255
Storrs, CT 06269-2155
[email protected]://www.engr.uconn.edu/
~stevehttp://www.engr.uconn.edu/cse
(860) 486 - 4818
CSE333
Java-1.2
Overview of PresentationOverview of Presentation
Motivation and Introduction to Java Motivation and Introduction to Java Designing and Developing Applets in JavaDesigning and Developing Applets in Java The Java User Interface - GUI with AWTThe Java User Interface - GUI with AWT Designing and Developing Java Classes Designing and Developing Java Classes Inheritance and Interfaces in JavaInheritance and Interfaces in Java Polymorphism and Object SerializationPolymorphism and Object Serialization
CSE333
Java-1.3
Motivation and Introduction to JavaMotivation and Introduction to Java
Java is Emerging as the OO Language of ChoiceJava is Emerging as the OO Language of Choice Java’s Utilization in … Java’s Utilization in …
Distributed Internet-Based Applications of All Types
Legacy/COTS Integration for Enterprise Computing
General-Purpose, Single-CPU Development Significant Dissemination on WWW:Significant Dissemination on WWW:
http://www.javasoft.com http://www.gamelan.com
We’ll Overview Key Features and CapabilitiesWe’ll Overview Key Features and Capabilities
CSE333
Java-1.4
An Overview of JavaAn Overview of Java
Java is a Third Generation, General Purpose, Java is a Third Generation, General Purpose, Platform Independent, Concurrent, Class-Based, Platform Independent, Concurrent, Class-Based, Object-Oriented Language and EnvironmentObject-Oriented Language and Environment
Java Composed of JDK and JREJava Composed of JDK and JRE Java LanguageJava Language Java Packages (Libraries)Java Packages (Libraries) javac Compiler to Bytecode (p-code)javac Compiler to Bytecode (p-code) JDB Java Debugger JDB Java Debugger Java Interpreter - Platform SpecificJava Interpreter - Platform Specific
JDK: Java Development EnvironmentJDK: Java Development Environment http://www.javasoft.com/products/jdk/1.2/http://www.javasoft.com/products/jdk/1.2/
JRE: Java Runtime EnvironmentJRE: Java Runtime Environment http://www.javasoft.com/products/jdk/1.2/jre/index.html
CSE333
Java-1.5
What is Java?What is Java?Software Releases and IDEsSoftware Releases and IDEs
Java is Free!Java is Free! Current Releases Current Releases
Version 2 for Win95, Win98, NT Version 2 (Early Access) for Solaris
Third-Party Ports to All Conceivable HW/SW Third-Party Ports to All Conceivable HW/SW Platforms from Micros to Mainframes Platforms from Micros to Mainframes
http://www.javasoft.com/cgi-bin/java-ports.cgi
Integrated Development Environments (IDEs) Integrated Development Environments (IDEs) Commercial Products, Freeware, Visual IDEs Visual J++, Visual Café, Kawa, Jpad, Javelin
CSE333
Java-1.6
Java Virtual Machine (JVM)Java Virtual Machine (JVM)
JVM is a JVM is a Platform Specific ProgramPlatform Specific Program which which Interprets and Executes Java CodeInterprets and Executes Java Code
JVM Interprets and Executes BytecodesJVM Interprets and Executes Bytecodes
JVM Targeted as Small/Efficient - Embeddable JVM Targeted as Small/Efficient - Embeddable within Consumer Electronicswithin Consumer Electronics
JVM Stack Based Machine - Simulates Real JVM Stack Based Machine - Simulates Real ProcessorProcessor
CA FE BA BE 00 03 00 2D 00 3ECA FE BA BE 00 03 00 2D 00 3E08 00 3B 08 00 01 08 00 20 0808 00 3B 08 00 01 08 00 20 08
CSE333
Java-1.7
Java Visualization Java Visualization
CSE333
Java-1.8
Packages In JavaPackages In Java
Allows Related Classes to be Grouped into a Allows Related Classes to be Grouped into a Larger AbstractionLarger Abstraction Similar to Ada95 Packages Unavailable in C++
Utilization of Packages for SW Design and Utilization of Packages for SW Design and DevelopmentDevelopment Components, Modularization, Groupings Enforcement by Compiler of Package Rules
Overall, Packages Enhance the Control and Overall, Packages Enhance the Control and Visibility to Fine-Tune Visibility to Fine-Tune Who Can See What When
CSE333
Java-1.9
The Java API PackagesThe Java API Packages
Application Programming Interface (API)Application Programming Interface (API) Java Defined - Building Blocks/LibrariesJava Defined - Building Blocks/Libraries Java Platform 1.2/2 Core APIJava Platform 1.2/2 Core API
java.applet java.rmijava.awt java.rmi.dgcjava.awt.datatransfer java.rmi.registryjava.awt.event java.rmi.serverjava.awt.image java.securityjava.beans java.security.acljava.io java.security.interfacesjava.lang java.sqljava.lang.reflect java.textjava.math java.utiljava.net java.util.zip
Power of Java Contained with APIsPower of Java Contained with APIs
CSE333
Java-1.10
The Java LanguageThe Java Language
Overview of Non-OO CapabilitiesOverview of Non-OO Capabilities Based on C/C++ No includes, typedefs, structures, groups Unicode Character Set - 34,168 Characters Automatic Coercions Not Supported Strongly-Type Language
Variables in JavaVariables in Java Primitive Types: ints, floats, booleans,
Unicode chars Reference Types: arrays, classes, interfaces
No Physical Pointers in Java!No Physical Pointers in Java!
CSE333
Java-1.11
The Java LanguageThe Java Language
Statements in Java - Resembles C and C++Statements in Java - Resembles C and C++ Assignment/Expressions and Precedence for, while, do-while if-then, switch-case break, continue, label, return
Exception HandlingException Handling Similar to C++ try, throws, catch Blocks Strongly Integrated Throughout APIs
CSE333
Java-1.12
The Java LanguageThe Java LanguageMotivating the Class ConceptMotivating the Class Concept
Conceptually, Classes are Structures/Records Conceptually, Classes are Structures/Records with Functions that are Encapsulatedwith Functions that are Encapsulated
structure Item { int UPC, OnShelf, InStock, ROLimit; char* Name; float RCost, WCost;
Status Create_New_Item(int UPC, ...); NameCost* Get_Item_NameCost(int UPC); void Modify_Inventory(int UPC, int Delta) ; Boolean Check_If_On_Shelf(int UPC); Boolean Time_To_Reorder(int UPC); };
NameCost *nc;Item I1, I2;I1.Create_New_Item(...);nc = I2.Get_Item_NameCost(UPC);
CSE333
Java-1.13
The Java LanguageThe Java LanguageObject-Oriented FeaturesObject-Oriented Features
Class - similar to C++ ClassClass - similar to C++ Class Classes have Classes have MembersMembers ( (MethodsMethods and and VariablesVariables)) Members Tagged Using Members Tagged Using KeywordsKeywords
private: Typically, Inaccessible public: Potential to be Accessible protected: Accessible via Inheritance package: Accessible within Package
Involve Visible Between Classes, Within Involve Visible Between Classes, Within Packages, and Due to InheritancePackages, and Due to Inheritance
CSE333
Java-1.14
Classes in JavaClasses in Java
A Supermarket ItemA Supermarket Item Keywords must be Utilized for Each Attribute Keywords must be Utilized for Each Attribute
or Method Declarationor Method Declaration
class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost;
public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta){...}; public int Get_InStock_Amt() {return Quantity;};};
CSE333
Java-1.15
Classes in JavaClasses in Java
class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost;
public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta) { int i = Get_InStock_Amt (); if (Delta >= 0) { Quantity += Delta; return true; } else { return false;} }; public int Get_InStock_Amt() {return Quantity;}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(); {...};};
CSE333
Java-1.16
Visibility of Attributes/MethodsVisibility of Attributes/Methods
Class Members (Attributes and Methods)Class Members (Attributes and Methods) Visibility Tags for MembersVisibility Tags for Members
Private: Visible only to Class Protected: Visible to Class and Other Classes
within Package Public: Visible to Class, Other Classes within
Package, and if Class is Public, Visible to Other Packages/Classes
No Tag: Visible Only to Other Classes within Defining Package
Java's Controlled Sharing within/between Packages Java's Controlled Sharing within/between Packages not Supported in C++not Supported in C++
Abstraction/Encapsulation Superior in Java!Abstraction/Encapsulation Superior in Java!
CSE333
Java-1.17
Inheritance - Two RolesInheritance - Two Roles
Controlled Sharing Between ClassesControlled Sharing Between Classes Generalization vs. Specialization
Treat Instances of Different Classes in a Treat Instances of Different Classes in a Uniform FashionUniform Fashion Polymorphism and Dynamic Binding
Inheritance in JavaInheritance in Java
Item / \ DeliItem ProduceItem | SaladItem
class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... };
CSE333
Java-1.18
Designing and Developing Applets in JavaDesigning and Developing Applets in Java
Applets Small Independent Programs Intended for Applets Small Independent Programs Intended for Embedding into WWW Pages and Executable via Embedding into WWW Pages and Executable via Java-Enabled Browser (Netscape or IE)Java-Enabled Browser (Netscape or IE)
Applets Operate Under Severe Security Limits:Applets Operate Under Severe Security Limits: Can’t Execute Local Programs Can’t Communicate with Host Other than one
from Which Downloaded Can’t Read/Write to Local File System Can’t Find Information on Local System
Except Java/OS Versions and Character/Line Separators
CSE333
Java-1.19
Designing and Developing Applets in JavaDesigning and Developing Applets in Java
An Applet is a Java Program that Executes as An Applet is a Java Program that Executes as part of an HTML Pagepart of an HTML Page
appletA.java
appletA.class
javac
HTML file
...<APPLET CODE = “A.class”>
...
CSE333
Java-1.20
Applets Inheritance StructureApplets Inheritance Structure
java.lang.Objectjava.lang.Object
java.awt.Componentjava.awt.Component
java.awt.Containerjava.awt.Container
java.applet.Appletjava.applet.Applet
your appletyour applet
Everything in Java inherits from the Object class
Event-handling and drawing capabilities
Ability to hold components
Limits what an Applet can and cannot do
Every Applet is a subclass of the Applet class.
CSE333
Java-1.21
Applet Methods Eligible for OverridingApplet Methods Eligible for Overriding
Methods for MilestonesMethods for Milestones
initinit - initializes an - initializes an applet when it is loadedapplet when it is loaded
startstart - (re)starts applet’s - (re)starts applet’s executionexecution
stopstop - stops applet’s - stops applet’s executionexecution
destroydestroy - final cleanup - final cleanup before unloadingbefore unloading
Methods for DrawingMethods for Drawing
paintpaint updateupdate
The applet subclass must override at least one of these methods: init, start or paint.
CSE333
Java-1.22
Handling EventsHandling Events
Applets Handle Events by Implementing the Applets Handle Events by Implementing the Corresponding Corresponding interfaceinterface
import java.awt.event.MouseListener;import java.awt.event.MouseListener;import java.awt.event.MouseEvent;import java.awt.event.MouseEvent;……public class Simple extends Appletpublic class Simple extends Applet
implements implements MouseListener {MouseListener {
…… public void init() {public void init() { addMouseListener(this);addMouseListener(this); … … }} public void mouseClicked(MouseEvent event) {public void mouseClicked(MouseEvent event) { addItem(“click…”);addItem(“click…”); }}……}}
mouseClickedmouseEnteredmouseExitedmousePressedmouseReleased
Protocol of behavior
All methods in the interface must be implemented
CSE333
Java-1.23
Running an Applet in HTMLRunning an Applet in HTML
<APPLET CODE = <APPLET CODE = “AppletSubclass.class” WIDTH = “AppletSubclass.class” WIDTH = anIntanInt HEIGHT = HEIGHT = anIntanInt>>
</APPLET></APPLET>
The Browser:The Browser: Reserves a Display Area for the AppletReserves a Display Area for the Applet Loads the bytecodeLoads the bytecode Creates an Instance of the SubclassCreates an Instance of the Subclass Calls the Calls the initinit and and startstart Methods Methods
CSE333
Java-1.24
Loading an AppletLoading an Applet
Finding an AppletFinding an Applet CODEBASE Relative/Absolute Address
CODEBASE=“example/”CODEBASE=“http://someServer/…/otherDirectory/”
Bringing the AppletBringing the Applet Class by Class/Archives
HTMLfile Class
file
example
HTMLfile
Classfile
otherDirectory
CSE333
Java-1.25
The <APPLET> tagThe <APPLET> tag
<<APPLETAPPLET[[CODEBASECODEBASE = = codebaseURLcodebaseURL]]((CODECODE = = appletFileappletFile | | OBJECTOBJECT = = serializedAppletserializedApplet))[[ARCHIVEARCHIVE = = archivesListarchivesList]][[ALTALT = = alternateTextalternateText]][[NAMENAME = = appletInstanceNameappletInstanceName]]WIDTHWIDTH = = pixelspixels HEIGHTHEIGHT = = pixelspixels[[ALIGNALIGN = = alignmentalignment]][[VSPACEVSPACE = = pixelspixels] [] [HSPACEHSPACE = = pixelspixels]]>>[<[<PARAMPARAM NAMENAME = = appletParameter1appletParameter1 VALUEVALUE = = valuevalue>]>][<[<PARAMPARAM NAMENAME = = appletParameter2appletParameter2 VALUEVALUE = = valuevalue>]>]……[[alternateHTMLalternateHTML]]<</APPLET/APPLET>>
CSE333
Java-1.26
Security IssuesSecurity Issues
An Untrusted Applet Cannot:An Untrusted Applet Cannot: Load Libraries or Define Native Methods Read or Write Files on the Host that is
Executing the Applet Make Network Connections Except to the
Host from Which it was Loaded From Start any Program on the Host that is
Executing the Applet Get Many System Properties
CSE333
Java-1.27
Example of a GUI AppletExample of a GUI Applet
/* http://java.sun.com/docs/books/tutorial/ui/components/example//* http://java.sun.com/docs/books/tutorial/ui/components/example/ButtonDemo.java */ButtonDemo.java */
import java.awt.*;import java.awt.*;import java.awt.event.ActionListener;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import java.awt.event.ActionEvent;import java.applet.Applet;import java.applet.Applet;
public class ButtonDemo extends Appletpublic class ButtonDemo extends Applet implements ActionListener {implements ActionListener {
Button b1, b2, b3;Button b1, b2, b3;static final String DISABLE = "disable";static final String DISABLE = "disable";static final String ENABLE = "enable";static final String ENABLE = "enable";
public void init() {public void init() { b1 = new Button();b1 = new Button(); b1.setLabel("Disable middle button");b1.setLabel("Disable middle button"); b1.setActionCommand(DISABLE);b1.setActionCommand(DISABLE);
b2 = new Button("Middle button");b2 = new Button("Middle button");
b3 = new Button("Enable middle button");b3 = new Button("Enable middle button"); b3.setEnabled(false);b3.setEnabled(false); b3.setActionCommand(ENABLE);b3.setActionCommand(ENABLE);
CSE333
Java-1.28
Example of a GUI Applet (Continued)Example of a GUI Applet (Continued)
//Listen for actions on buttons 1 and 3.//Listen for actions on buttons 1 and 3. b1.addActionListener(this);b1.addActionListener(this); b3.addActionListener(this);b3.addActionListener(this);
//Add Components to the Applet, using the default FlowLayout. //Add Components to the Applet, using the default FlowLayout. add(b1);add(b1); add(b2);add(b2); add(b3);add(b3); }}
public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) { String command = e.getActionCommand();String command = e.getActionCommand(); if (command == DISABLE) { //They clicked "Disable middle button"if (command == DISABLE) { //They clicked "Disable middle button" b2.setEnabled(false);b2.setEnabled(false); b1.setEnabled(false);b1.setEnabled(false); b3.setEnabled(true);b3.setEnabled(true); } else { //They clicked "Enable middle button"} else { //They clicked "Enable middle button" b2.setEnabled(true);b2.setEnabled(true); b1.setEnabled(true);b1.setEnabled(true); b3.setEnabled(false);b3.setEnabled(false); }} }}}}
CSE333
Java-1.29
The Java User Interface - GUI with AWTThe Java User Interface - GUI with AWT
UI Refers to the Communications Between a UI Refers to the Communications Between a Program and a UserProgram and a User
Java Abstract Windowing Toolkit (AWT) and Java Abstract Windowing Toolkit (AWT) and Swing Contains Complete Set of Classes for Swing Contains Complete Set of Classes for Writing GUI ProgramsWriting GUI Programs
AWT Classes Categorized into: AWT Classes Categorized into: GUI Components Containers Layout Managers Drawing Event Handling
CSE333
Java-1.30
AWT ComponentsAWT Components
ButtonButton CheckBoxesCheckBoxes ChoicesChoices ListsLists MenusMenus TextfieldsTextfields Text AreasText Areas LabelsLabels
CSE333
Java-1.31
ContainersContainers
The Java AWT Provides Three Types of The Java AWT Provides Three Types of Containers Implemented as Subclasses of Containers Implemented as Subclasses of Container Class:Container Class: Window
Frame - creates a normal full fledged window to contain components
Dialog - provides a window that is dependent on another window
FileDialog - helps the user to open and save file Panel - Groups Components within an Area of
an Existing Window ScrollPane -Like Panel, Used to Display Large
Component in a Limited Amount of Space
CSE333
Java-1.32
Inheritance Hierarchies for ComponentsInheritance Hierarchies for Components
CSE333
Java-1.33
Layout ManagersLayout Managers
Layout Manager Controls the Size and Position of Layout Manager Controls the Size and Position of Components in a ContainerComponents in a Container
By Default Every Container Object has an By Default Every Container Object has an Associated LayoutMangerAssociated LayoutManger Panel Objects - FlowLayout Window Object - BorderLayout
CSE333
Java-1.34
Layout Managers - SimpleLayout Managers - Simple
FlowLayout FlowLayout Default for Panel
Objects Lays out Components
from Left to Right Starting New Rows if Needed
GridLayoutGridLayout Displays the
Components in Equal Size in the Requested Number of Rows and Columns
CSE333
Java-1.35
Layout Managers - Special PurposeLayout Managers - Special Purpose
BorderLayout BorderLayout Default for Window
Objects Uses 5 Areas to hold
Components: North, South, East, West, and Center
CardLayoutCardLayout One Area Contains
Different Components at Different Times
CSE333
Java-1.36
Layout Managers - FlexibleLayout Managers - Flexible
GridBagLayoutGridBagLayout Aligns Components by Placing them in a Grid
of Cells Allows some Components to Span more than
one Cell The Rows and Columns have Different Heights
and Widths
CSE333
Java-1.37
Example of a GUI appletExample of a GUI applet
CSE333
Java-1.38
Excerpts for GUI Applet ExampleExcerpts for GUI Applet Example(Note: Many Lines Omitted!!) (Note: Many Lines Omitted!!)
import java.applet.*;import java.awt.*;import Message;
public class Sample extends Applet { Panel p1, p2; Label l1, l2, l3, l4, l5; TextField name; TextArea address; Checkbox order; Choice size, color; Button ok, clear, quit ; Message message;
CSE333
Java-1.39
Excerpts for GUI Applet ExampleExcerpts for GUI Applet Example (Note: Many Lines Omitted!!) (Note: Many Lines Omitted!!)
public void init() { p1 = new Panel(); p2 = new Panel();
l1 = new Label("Name"); l2 = new Label("Address"); // … other labels omitted
name = new TextField(30);address = new TextArea(3, 30);
order = new Checkbox();size = new Choice();size.addItem("Small");size.disable();ok = new Button("OK");clear = new Button("Clear");quit = new Button("Quit");
p1.setLayout(new GridLayout(0,2,2,2));p1.add(l1);p1.add(name);p1.add(l2);p1.add(address);p1.add(l3);p1.add(order);p1.add(l4);p1.add(size);p1.add(l5);p1.add(color);p2.setLayout(new FlowLayout());p2.add(ok);p2.add(clear);p2.add(quit);setLayout(new BorderLayout());add("North", p1);add("South", p2);
}
CSE333
Java-1.40
Excerpts for GUI Applet ExampleExcerpts for GUI Applet Example (Note: Many Lines Omitted!!) (Note: Many Lines Omitted!!)
public boolean action(Event e, Object o){ if(e.target == ok)
{ // You must provide the actions/code}if(e.target == clear){ // You must provide the actions/code}if(e.target == quit){ // You must provide the actions/code
}if(e.target == order){
if(order.getState() == true){ // You must provide the actions/code}else if(order.getState() == false){ // You must provide the actions/code}
}return true;
}}
CSE333
Java-1.41
Event HandlingEvent Handling
When a User Acts on a Component, the AWT When a User Acts on a Component, the AWT Detects the Event and Notifies the Event ListenersDetects the Event and Notifies the Event Listeners
A Class Implements the Event Listener and Every A Class Implements the Event Listener and Every Class Instance can Register as Event ListenersClass Instance can Register as Event Listeners
Steps for Implementing and Registering:Steps for Implementing and Registering: Declare that a Class Implements a Listener
Interface in the Class declaration Implement the Listener methods in the Class Register an Instance of the Class as a Listener
on One or More Components
CSE333
Java-1.42
Example of Event HandlingExample of Event Handling
public class Beeper ... implements ActionListener { ... // where initialization occurs: button.addActionListener(this); ... public void actionPerformed(ActionEvent e)
{ // Make a beep sound ... }}
CSE333
Java-1.43
The AWT EventsThe AWT Events
Action Events Action Events Adjustment EventAdjustment Event Component Events Component Events Container EventsContainer Events Focus EventsFocus Events Item EventsItem Events Key EventsKey Events Mouse EventsMouse Events Mouse-Motion EventsMouse-Motion Events Text EventsText Events Window EventWindow Event
CSE333
Java-1.44
Action ListenersAction Listeners
Easiest Event Handlers to ImplementEasiest Event Handlers to Implement Generated by:Generated by:
Clicking a Button Double Clicking a List Item Choosing a Menu Item Pressing Return in a Text Field
Listener Interface - ActionListenerListener Interface - ActionListener Methods - actionPerformed(ActionEvent)Methods - actionPerformed(ActionEvent)
CSE333
Java-1.45
Action Listeners - ActionEventAction Listeners - ActionEvent
Parameter to the actionPerfomed MethodParameter to the actionPerfomed Method ActionEvent Defines Two Useful MethodsActionEvent Defines Two Useful Methods
String setActionCommand Associates a string to the action
String getActionCommand Returns the string associated with this action
CSE333
Java-1.46
Item ListenersItem Listeners
Generated by Components that Maintain State, Generated by Components that Maintain State, Generally on/off StateGenerally on/off State
Components that Generate ItemEvents:Components that Generate ItemEvents: Checkboxes Choices Lists
Listener Interface - ItemListenerListener Interface - ItemListener Methods - itemStateChanged(ItemEvent)Methods - itemStateChanged(ItemEvent)
CSE333
Java-1.47
ItemListeners - ItemEventItemListeners - ItemEvent
Parameter to the itemStateChanged MethodParameter to the itemStateChanged Method ItemEvent Defines Two Useful Methods:ItemEvent Defines Two Useful Methods:
Object getItem() Returns the component specific object associated
with the item whose state has changed int getStateChange()
Returns the new state of the item SELECTED = 1 DESELECTED = 0
CSE333
Java-1.48
Excerpts for GUI Applet with ListenerExcerpts for GUI Applet with Listener(Note: Many Lines Omitted!!) (Note: Many Lines Omitted!!)
import java.applet.*;import java.awt.*;import java.awt.event.*;import Message;
public class Sample1 extends Applet implements ActionListener, ItemListener
{// Declarations similar to previous example
static final String OK = "ok"; public void init() { // Init actions similar to previous example, // except for code shown below for checkbox and buttons order = new Checkbox(); order.addItemListener(this); ok = new Button("OK"); ok.setActionCommand(OK); ok.addActionListener(this); }
CSE333
Java-1.49
Excerpts for GUI Applet with ListenerExcerpts for GUI Applet with Listener(Note: Many Lines Omitted!!) (Note: Many Lines Omitted!!)
public void actionPerformed(ActionEvent e){ String command = e.getActionCommand();
if(command == OK) { // You must provide the actions/code }if(command == CLEAR) { // You must provide the actions/code }if(command == QUIT) { // You must provide the actions/code }
}
public void itemStateChanged(ItemEvent e1){ if(e1.getStateChange() == ItemEvent.SELECTED)
{ // You must provide the actions/code}else { // You must provide the actions/code}
}}
CSE333
Java-1.50
Designing and Developing Java ClassesDesigning and Developing Java Classes
Encapsulation Capabilities of JavaEncapsulation Capabilities of Java Classes (Data + Operations) - ADTs Packages - Collections of “Related” Classes
Class Declaration:Class Declaration: Access Modes and Variable Members Constructors and Class Bodies Method Declaration and Access Modes Class and Instance Members Garbage Collection
CSE333
Java-1.51
Class DefinitionClass Definition
public class Stack {public class Stack { private Vector items;private Vector items; public Stack() {public Stack() { items = new Vector(10);items = new Vector(10); }} public Stack(int numElem) {public Stack(int numElem) { items = new Vector(numElem);items = new Vector(numElem); }} public Object push(Object item) {public Object push(Object item) { item.addElement(item);item.addElement(item); return item;return item; }} public synchronized Object pop() {public synchronized Object pop() { int len = items.size();int len = items.size(); Object obj = null;Object obj = null; if (len == 0)if (len == 0) throw new EmptyStackException();throw new EmptyStackException(); obj = items.elementAt(len - 1);obj = items.elementAt(len - 1); items.removeElementAt(len - 1);items.removeElementAt(len - 1); return obj;return obj; }} public boolean isEmpty() {public boolean isEmpty() { if (items.size() == 0)if (items.size() == 0) return true;return true; elseelse return false;return false; }}}}
Class Body
Class DeclarationMemberVariable
Constructors
MemberMethods
CSE333
Java-1.52
PackagesPackages
A A packagepackage is a Collection of Related Classes and is a Collection of Related Classes and Interfaces that Provides Access Protection and Interfaces that Provides Access Protection and Namespace ManagementNamespace Management
File Name and Package Name IdenticalFile Name and Package Name Identical Packages are Imported via the Packages are Imported via the importimport Keyword Keyword
package graphics;class Circle extend Graphic implements Draggable { ... }class Rectangle extends Graphic implements Draggable { ... }interface Draggable { ... }
CSE333
Java-1.53
Access ModesAccess Modes
Constructors and Members Constructors and Members can be defined as:can be defined as: public: Any other class
can invoke them. protected: Only
subclasses and classes in the same package can invoke them.
private: Only accessible within the class.
package: Accessible only to other classes and interfaces declared in the same package (default if omitted).
Controls Encapsulation Controls Encapsulation and Allows Evolvability and Allows Evolvability with Minimal Impact on with Minimal Impact on other Classes that use the other Classes that use the MembersMembers
Deciding Appropriate Deciding Appropriate Access Mode Access Mode Determines Security and Determines Security and Ensures that Data Ensures that Data Remains in a Consistent Remains in a Consistent State.State.
CSE333
Java-1.54
ConstructorsConstructors
Utilized to Create a new Class instance by Utilized to Create a new Class instance by Reserving Sspace for the Member Variables Reserving Sspace for the Member Variables Rectangle rect = Rectangle rect = newnew Rectangle(); Rectangle();
Member Variable Initialization PossibleMember Variable Initialization Possible Constructors Mimic Class Name with No Return Constructors Mimic Class Name with No Return
TypeType Default Constructor with Empty Argument ListDefault Constructor with Empty Argument List Constructors may be OverloadedConstructors may be Overloaded
CSE333
Java-1.55
Variable MembersVariable Members
Declaration (Class Body)Declaration (Class Body) Defines the Type of a Variable
Instantiation (Constructor)Instantiation (Constructor) Reserves Memory for the New Instance
InitializationInitialization Assign Initial Value(s)
accessLevel Indicates the access level of this memberstatic Declares a class memberfinal Indicates that it is constanttransient This variable is transientvolatile This variable is volatiletype name The type and name of the variable
CSE333
Java-1.56
Method MembersMethod Members
DeclarationDeclaration Access Level
public, protected, private, or package Return Type
void or type return statement Either return the declared type or a subtype
Name Overloading Overriding
Arguments List of variable declarations Cannot include methods Argument names may hide member names: this
CSE333
Java-1.57
accessLevel Access level for this methodstatic This is a class methodabstract This method is not implementedfinal Method cannot be overridennative Method implemented in another languagesynchronized Method requires a monitor to runreturnType methodName The return type and the method name(paramlist) The list of argumentsthrows exceptions The exceptions thrown by this method
Method Members (cont.)Method Members (cont.)
CSE333
Java-1.58
ExampleExamplepublic class Point {public class Point { public int x = 0;public int x = 0; public int y = 0;public int y = 0;
public void move(int newX, int newY) {public void move(int newX, int newY) { x = newX;x = newX; y = newY;y = newY; }}}}
public class Line {public class Line { public Point origin;public Point origin; public Point end;public Point end;
public Line() {public Line() { origin = new Point();origin = new Point(); end = new Point();end = new Point(); }} public Line(Point origin, Point end) {public Line(Point origin, Point end) { this.origin = origin;this.origin = origin; this.end = end;this.end = end; }}}}
DefaultConstructor
Overloading
Hiding
origin end
x
y
x
y
aLineObject
LineInstance
PointInstances
CSE333
Java-1.59
Class and Instance MembersClass and Instance Members
Class Members are Defined with the Keyword Class Members are Defined with the Keyword staticstatic
Class Variables and Class Methods are Associated Class Variables and Class Methods are Associated with the Class Rather than each of its Instanceswith the Class Rather than each of its Instances
Class Variables are Shared Among all InstancesClass Variables are Shared Among all Instances JRE Creates one copy of Class Variables the First JRE Creates one copy of Class Variables the First
Time it Encounters a Containing InstanceTime it Encounters a Containing Instance Class Methods only Operate on Class VariablesClass Methods only Operate on Class Variables Class Bariables declared as Class Bariables declared as finalfinal are constants are constants Class Members are Accessible without the need to Class Members are Accessible without the need to
Instantiate the ClassInstantiate the ClassclassName.classMethod();className.classVar = 10;
CSE333
Java-1.60
Class and Instance Members (Continued)Class and Instance Members (Continued)
class AnInteger { int x; public int x() { return x; } public void setX(int newX) { x = newX; }}
class AnInteger { static int x; public int x() { return x; } public void setX(int newX) { x = newX; }}
…AnInteger myX = new AnInteger();AnInteger yourX = new AnInteger();myX.setX(1);yourX.x = 2;System.out.println(“myX = “ + myX.x());System.out.println(“yourX = “ + yourX.x());…
class AnInteger { int x; static public int x() { return x; } static public void setX(int newX){ x = newX; }}
CSE333
Java-1.61
Garbage CollectionGarbage Collection
Unreferenced Objects are Garbage Collected Unreferenced Objects are Garbage Collected AutomaticallyAutomatically
Memory is Freed for Later ReuseMemory is Freed for Later Reuse Garbage Collection runs in a Low Priority Thread, Garbage Collection runs in a Low Priority Thread,
either Synchronously or Asynchronouslyeither Synchronously or Asynchronously The The finalize()finalize() Method is Inherited from Method is Inherited from
ObjectObject and can be Overridden to Liberate and can be Overridden to Liberate ResourcesResources
CSE333
Java-1.62
Inheritance in JavaInheritance in Java
Basic Definitions and ConceptsBasic Definitions and Concepts Generalization vs. Specialization Subclass vs. Superclass
Acquisition Rules Acquisition Rules What Does Superclass Pass to Subclass? What Does Subclass Inherit from Superclass? What is Visible within Packages? Overriding vs. Overloading?
Role of Public, Final, and Abstract ClassesRole of Public, Final, and Abstract Classes Java Interfaces for Design-Level Multiple Java Interfaces for Design-Level Multiple
Inheritance and Quasi GenericsInheritance and Quasi Generics
CSE333
Java-1.63
Inheritance - Terms and ConceptsInheritance - Terms and Concepts
Every Class in Java is Derived from the Object Every Class in Java is Derived from the Object ClassClass
Java Classes can be Organized into Hierarchies Java Classes can be Organized into Hierarchies Using the Using the extendsextends Keyword Keyword
Establishing Establishing Superclass/SubclassSuperclass/Subclass Relationships Relationships Between the Classes in ApplicationBetween the Classes in Application
A A SuperclassSuperclass Contains Members Common to Its Contains Members Common to Its SubclassesSubclasses - - GeneralizationGeneralization
SubclassesSubclasses Contain Members Different from Contain Members Different from Shared Shared SuperclassSuperclass - - SpecializationSpecialization
Only Single Inheritance is Supported in Java at Only Single Inheritance is Supported in Java at Implementation Level!Implementation Level!
CSE333
Java-1.64
Subclass & SuperclassSubclass & Superclass
Subclass Subclass Subclass is a Class that Extends Another Class Inherits State and Behavior from all of its
Ancestors Subclass can use the Inherited Member
Variables and Functions oror hide the Inherited Member Variables and Override the Inherited Member Functions
SuperclassSuperclass Superclass is a Class’s Direct Ancestor
CSE333
Java-1.65
A Superclass in JavaA Superclass in Java
A Supermarket ItemA Supermarket Item Keywords must be Utilized for Each Attribute Keywords must be Utilized for Each Attribute
or Method Declarationor Method Declaration
class Item { private String UPC, Name; private int Quantity; private double RetailCost; protected double WholeCost;
public Item() { ... }; public void finalize() { ... }; public boolean Modify_Inventory(int Delta){...}; public int Get_InStock_Amt() {return Quantity;};};
CSE333
Java-1.66
Inheritance - Defining Subclasses in JavaInheritance - Defining Subclasses in Java
ItemItem / \/ \ DeliItem ProduceItemDeliItem ProduceItem || SaladItemSaladItem
class DeliItem extends Item { ... }; class SaladItem extends DeliItem { ... }; class ProduceItem extends Item { ... };
CSE333
Java-1.67
Members Inherited By a SubclassMembers Inherited By a Subclass
Subclass Inherits all Public/Protected Members Subclass Inherits all Public/Protected Members of a Superclassof a Superclass DeliItem Inherits Public/Protected from
Item Subclass Inherits all Package Members of Subclass Inherits all Package Members of
Classes in the same Package as the SubclassClasses in the same Package as the Subclass All superclass Members can be Declared with All superclass Members can be Declared with
no Access Specification, if Subclass is in the no Access Specification, if Subclass is in the Same Package as the SuperclassSame Package as the Superclass
CSE333
Java-1.68
Members Not Inherited By A SubclassMembers Not Inherited By A Subclass
Subclass does not Inherit Private Members of a Subclass does not Inherit Private Members of a SuperclassSuperclass DeliItem doesn’t Inherit Private from Item
Subclasses do not Inherit a Superclass’s Member if Subclasses do not Inherit a Superclass’s Member if the Subclass Declares a Member with Same Namethe Subclass Declares a Member with Same Name Member Variables - Subclass Hides the
Member Variable of the Superclass Member Methods - Subclass Overrides the one
in the Superclass
CSE333
Java-1.69
Hiding Member Variables Hiding Member Variables and Overriding Member Methodsand Overriding Member Methods
class parentClass {boolean state;void setState() {
state = true;}
}class childClass extends parentClass {
boolean state;void setState() {
state = false;super.setState();System.out.println(state);System.out.println(super.state)
}}
CSE333
Java-1.70
Overriding Member MethodsOverriding Member Methods
Subclasses CANNOT Override Methods that are Subclasses CANNOT Override Methods that are Declared to be Final in the SuperclassDeclared to be Final in the Superclass
Subclasses MUST Override Methods that are Subclasses MUST Override Methods that are Declared as Abstract in the SuperclassDeclared as Abstract in the Superclass
Subclasses MUST be Declared as Abstract if they Subclasses MUST be Declared as Abstract if they do not Override Abstract Methods from the do not Override Abstract Methods from the SuperclassSuperclass
CSE333
Java-1.71
Methods Inherited From Methods Inherited From ObjectObject Class Class
The Java “The Java “ObjectObject” Class Defines Basic State and ” Class Defines Basic State and Behavior of all Classes and Their InstancesBehavior of all Classes and Their Instances
User Defined Classes can Override these Methods:User Defined Classes can Override these Methods: clone equals finalize toString hashCode
User Defined Classes Cannot Override: User Defined Classes Cannot Override: getClass notify notifyAll wait
CSE333
Java-1.72
Public, Final, and Abstract ClassesPublic, Final, and Abstract Classes
Public ClassesPublic Classes Within Package, public Classes Become
Visible to Outside World Public Members are Exported
Final ClassesFinal Classes Prohibits Subclassing for Security Final Class Prevents Access of Protected
Members via Subclassing Not Supported in C++/Ada95
Abstract ClassesAbstract Classes Can't be Instantiated No Implementations for Abstract Methods
CSE333
Java-1.73
Final Classes and Final Classes and the “Final” Keywordthe “Final” Keyword
A Class is Declared as Final - the Class Cannot be A Class is Declared as Final - the Class Cannot be Subclassed.Subclassed. For Security For Design
A Method is Declared as Final in a Class - any A Method is Declared as Final in a Class - any Subclass Cannot Override that MethodSubclass Cannot Override that Method
A Variable is Declared as Final - the Variable is a A Variable is Declared as Final - the Variable is a Constant and it Cannot be ChangedConstant and it Cannot be Changed
CSE333
Java-1.74
Abstract Classes And MethodsAbstract Classes And Methods
Abstract ClassesAbstract Classes Cannot be Instantiated Can only be Subclassed Keyword “abstract” before Keyword “class” is
used to Define an Abstract Class Example of an Abstract Class is Number in the
java.lang Package Abstract MethodsAbstract Methods
Abstract Classes may contain Abstract Methods
This allows an Abstract Class to Provide all its Subclasses with the Method Declarations for all the Methods
CSE333
Java-1.75
A Sample Abstract ClassA Sample Abstract Class
abstract class Item { protected String UPC, Name; protected int Quantity; protected double RetailCost, WholeCost;
public Item() { ... }; abstract public void finalize(); abstract public boolean Modify_Inventory(int Delta); public int Get_InStock_Amt() {...}; public double Compute_Item_Profit() {...}; protected boolean Modify_WholeSale(double NewPrice);{...}; };
CSE333
Java-1.76
Another Abstract Class and MethodsAnother Abstract Class and Methods
abstract class GraphicsObject{int x, y;void moveTo(int x1,y1) { . . . . . }abstract void draw();
}
class Circle extends GraphicsObject{void draw() { . . . . . }
}
class Rectangle extends GraphicsObject{void draw() { . . . . . }
CSE333
Java-1.77
Interfaces in JavaInterfaces in Java
Design-Level Multiple InheritanceDesign-Level Multiple Inheritance Java InterfaceJava Interface
Set of Methods (no Implementations) Set (Possibly Empty) of Constant Values
Interfaces Utilized Extensively Throughout Java Interfaces Utilized Extensively Throughout Java APIs to Acquire and Pass on FunctionalityAPIs to Acquire and Pass on Functionality Threads in Java - Multiple Concurrent Tasks Subclassing from Thread Class (java.lang API) Implementing an Interface of Runnable Class
CSE333
Java-1.78
A Sample Interface in JavaA Sample Interface in Java
Teaching
Student Employee / \ | UnderGrad Graduate Faculty
interface Teaching { int NUMSTUDENTS = 25; void recordgrade(Undergrad u, int score); void advise(Undergrad u); ... etc ... }
class Graduate extends Student implements Teaching{ ...}
class Faculty extends Employee implements Teaching{ ...}
recordgrade() Different for Graduate & Faculty
CSE333
Java-1.79
Quasi Generics in JavaQuasi Generics in Java
interface Coll { int MAXIMUM = 500; void add(Object obj); void delete(Object obj); Object find(Object obj); int currentCount();}
class Set implements Coll{ void add(Object obj){ ... } void delete(Object obj){ ... }}
class Queue implements Coll{ void add(Object obj){ ... } void delete(Object obj){ ... }}
CSE333
Java-1.80
Polymorphism and Polymorphism and Object Serialization in JavaObject Serialization in Java
PolymorphismPolymorphism Polymorphism via Dispatching Allows a
Runtime or Dynamic Choice of the Method to be Called based on the Class Type of the Invoking Instance
Promotes Reuse and Evolution of Code Polymorphism/Dispatching Incurs Cost or
Overhead at both Compile and Runtime! SerializationSerialization
Conversion of Object to Format that Facilitates Storage to File or Transfer Across Network
Process Controlled via API with Minimal Interaction by Software Engineer
CSE333
Java-1.81
PolymorphismPolymorphism
SubstitutabilitySubstitutability Whenever Value of a Certain Type is
Expected, a Subtype can also be Provided In Context of Inheritance, All Subclasses can
be Treated as Common Root Class Simplifies Code and Facilitates Reuse
Static TypeStatic Type Type Defined in the Variable Declaration
Dynamic TypeDynamic Type Type of the Actual Value held by the Variable
at Runtime
CSE333
Java-1.82
PolymorphismPolymorphism
A Variable is Polymorphic Whenever it may have A Variable is Polymorphic Whenever it may have Different Static and Dynamic TypesDifferent Static and Dynamic Types Static Variable I1 Defined with Type Item Dynamic Variable Access Allows I1.Print()
to be Invoked on DeliItem, ProduceItem, etc., Instances
Problems:Problems: Reverse Polymorphism: Can we get the
Subtype Variable Back After Assigning its Value to a Supertype?
Method Binding: When Invoking a Method on a Variable, should it be Selected According to its Static or Dynamic Type?
CSE333
Java-1.83
An ExampleAn Example
We have a class We have a class BallBall, and , and two subclasses two subclasses WhiteBallWhiteBall and and BlackBallBlackBall
The The SelectOneSelectOne() method () method gets a gets a WhiteBallWhiteBall and a and a BlackBallBlackBall as arguments and as arguments and returns one of them returns one of them selected randomly selected randomly
Questions:Questions: What is SelectOne()’s
return type? How can we know
which ball was returned?
SelectOne
?
CSE333
Java-1.84
Dynamic Binding and CastingDynamic Binding and Castingpublic class Ball { public String id = new String("I'm a
ball");
public String GetId() { return id; }}public class WhiteBall extends Ball { public String id = new String("I'm
white"); public String GetId() { return id; } public void OnlyWhite() { System.out.println("Yes, I'm
white"); }}public class BlackBall extends Ball { public String id = new String("I'm
black"); public String GetId() { return id; } public void OnlyBlack() { System.out.println("Yes, I'm
black"); }}
class balls {class balls { public static void main(String[] args) public static void main(String[] args)
{{ WhiteBall wb = new WhiteBall();WhiteBall wb = new WhiteBall(); BlackBall bb = new BlackBall();BlackBall bb = new BlackBall(); Ball b = SelectOne(wb, bb);Ball b = SelectOne(wb, bb); System.out.println(b.GetId());System.out.println(b.GetId()); System.out.println(b.id);System.out.println(b.id); if (b instanceof WhiteBall) {if (b instanceof WhiteBall) { wb = (WhiteBall)b;wb = (WhiteBall)b; wb.OnlyWhite();wb.OnlyWhite(); } else {} else { bb = (BlackBall)b;bb = (BlackBall)b; bb.OnlyBlack();bb.OnlyBlack(); }} }} public static Ball SelectOne(WhiteBall public static Ball SelectOne(WhiteBall
w, BlackBall b) {w, BlackBall b) { if (Math.random() > 0.5)if (Math.random() > 0.5) return w;return w; elseelse return b;return b; }}}}
The static type of b is Ball, but its dynamic type is either WhiteBallor BlackBall.
What is going to be printed?
CSE333
Java-1.85
Class Student (Superclass) - Maintains Class Student (Superclass) - Maintains Student InformationStudent Information
public class Student{ // protected used to facilitate
inheritance protected String name, SSN; protected float gpa; // constructor used to initialize
object public Student(String n, String
ssn,float g) { name = n; SSN = ssn; gpa = g; }
public String getName() { return name; }
public float getGpa() { return gpa; }
public String getSSN() { return SSN; }
// diplay student information public void print() { System.out.println("Student
name: " + name); System.out.println("
SSN: " + SSN); System.out.println("
gpa: " + gpa); }}
CSE333
Java-1.86
Class GradClass Grad
public class Grad extends Student{ private String thesis; public Grad(String name, String ssn, float gpa, String t) { // call parent's constructor super(name, ssn, gpa); thesis = t; }
public String getThesis() { return thesis; }
public void print() { super.print(); System.out.println(" thesis: " + thesis); }}
CSE333
Java-1.87
Class UndergradClass Undergrad
public class Undergrad extends Student { private String advisor; private String major;
public Undergrad(String name, String ssn, float gpa, String adv, String maj){
super(name, ssn, gpa); advisor = adv; major = maj; } public String getAdvisor() { return advisor; }
public String getMajor() { return major; }
public void print() { super.print(); System.out.println(" advisor: " + advisor); System.out.println(" major: " + major); }}
CSE333
Java-1.88
Class StudentDBClass StudentDB
import java.util.Vector;
public class StudentDB{ private Vector stuList;
// constructor public StudentDB(int size){ // allocate memory for
vector stuList = new
Vector(size); }
// returns number of students stored
public int numOfStudents() { return (stuList.size()); }
public void insert(Student s) { stuList.addElement(s); }
// search for student by name public Student
findByName(String name){ Student stu = null; //
temp student boolean found = false; int count = 0; int DBSize =
stuList.size(); while ((count < DBSize)||
(found == false)){ stu = (Student)
stuList.elementAt(count); if
(stu.getName().equals(name))
found = true;
count++; } return stu; }
CSE333
Java-1.89
Class StudentDB (Continued)Class StudentDB (Continued)
public Student remove(String name) { Student stu = null; // temp
student boolean found = false; int count = 0; int DBSize = stuList.size(); while ((count < DBSize) ||
(found == false)){ stu = (Student)
stuList.elementAt(count); if
(stu.getName().equals(name)) found = true; count++; } if (found == true)
stuList.removeElementAt(count - 1);
return stu; }
public void displayAll() { int DBSize =
stuList.size(); for (int i = 0; i <
DBSize; i++) { Student stu = (Student)
stuList.elementAt(i); stu.print(); System.out.println(); } }}
CSE333
Java-1.90
Class MainInterfaceClass MainInterface
public class MainInterface{ private StudentDB db;
public static void main(String[] args) {
MainInterface studentInt = new MainInterface();
studentInt.displayMenu(); } // constructor public MainInterface() { db = new StudentDB(5); }
public void displayMenu(){ int option = 0; System.out.println("\n 1. Insert "); System.out.println(" 2. Delete "); System.out.println(" 3. Search "); System.out.println(" 4. Display "); System.out.println(" 5. Exit \n"); option = Console.readInt("Enter your
choice: "); while (option > 0 && option < 5) { processOption(option); System.out.println("\n 1. Insert "); System.out.println(" 2. Delete"); System.out.println(" 3. Search "); System.out.println(" 4. Display "); System.out.println(" 5. Exit \n"); option = Console.readInt("Enter your
choice: "); } }
CSE333
Java-1.91
Class MainInterface (Continued)Class MainInterface (Continued)
public void processOption(int option) { String name, SSN; float gpa; switch (option){ case 1: int type = Console.readInt("1. Grad or 2. Undergrad? "); name = Console.readString(“Name: "); SSN = Console.readString(“SSN: "); gpa = (float) Console.readDouble("gpa: "); if (type == 1){ String thesis = Console.readString("Enter thesis title:"); Student g = new Grad(name, SSN, gpa, thesis); db.insert(g); }
CSE333
Java-1.92
Class MainInterface (Continued)Class MainInterface (Continued)
else{ String advisor = Console.readString("Enter
advisor:"); String major = Console.readString("Enter major: "); Student u = new Undergrad(name, SSN, gpa, advisor,
major); db.insert(u); } break; case 2: name = Console.readString(”Name"); Student s = db.remove(name); s.print(); break;
CSE333
Java-1.93
Class MainInterface (Continued)Class MainInterface (Continued)
case 3: name = Console.readString("Enter name: "); Student stu = db.findByName(name); System.out.println(); stu.print(); break; case 4: System.out.println(); db.displayAll(); } }}
CSE333
Java-1.94
Object SerializationObject Serialization
Object Serialization is the Process of Reading Object Serialization is the Process of Reading and Writing Objectsand Writing Objects Bi-directional Process of Write (Save in
Serialized form) and Read (Reconstruct from Serialized form)
ObjectInputStream and ObjectOutputStream are ObjectInputStream and ObjectOutputStream are used for Reading and Writing Objectsused for Reading and Writing Objects
Used in:Used in: Remote Method Invocation (RMI) Lightweight Persistence - Archival for Use
in a Later Invocation of a Program Exchange of Information Across Network Agent-Based/Aglet Computing
CSE333
Java-1.95
Using Object SerializationUsing Object Serialization
Straightforward Process in JavaStraightforward Process in Java Serialize Objects by ...Serialize Objects by ...
Writing Objects to an ObjectOutputStream Deserialize Objects by ...Deserialize Objects by ...
Reading Objects using ObjectInputStream Design/Develop Classes that Promote the Design/Develop Classes that Promote the
Serialization/Deserialization of InstancesSerialization/Deserialization of Instances Serialize/Deserialize at Topmost Level:Serialize/Deserialize at Topmost Level:
Automatically Includes Component Instances, Set and Collection Instances, User-Defined Class Instances, etc.
Whatever is Declared with Class and Active within Instance
CSE333
Java-1.96
Writing to an ObjectOutputStreamWriting to an ObjectOutputStream
The Following Code Segment Serializes the Date The Following Code Segment Serializes the Date ObjectObject FileOutputStream out = new
FileOutputStream("theTime"); ObjectOutputStream s = new ObjectOutputStream(out); s.writeObject("Today"); s.writeObject(new Date()); s.flush();
Serializes the Object to a File named “theTime”Serializes the Object to a File named “theTime”
CSE333
Java-1.97
Reading From an ObjectInputStreamReading From an ObjectInputStream
The Following Code Segment Reconstructs by The Following Code Segment Reconstructs by Deserializing the Date Object:Deserializing the Date Object:
FileInputStream in = new FileInputStream("theTime");ObjectInputStream s = new ObjectInputStream(in);String today = (String)s.readObject();Date date = (Date)s.readObject();
Object and its Components (if any) are Read from Object and its Components (if any) are Read from the File “theTime”the File “theTime”
If Multiple Independent Objects were Written, If Multiple Independent Objects were Written, Objects must be Read in the Same Order Objects must be Read in the Same Order
Return Value from readObject has to be Cast to a Return Value from readObject has to be Cast to a Specific TypeSpecific Type
CSE333
Java-1.98
Utilizing Object SerializationUtilizing Object Serialization
Serialization/Deserialization Occurs via the Serialization/Deserialization Occurs via the Implementation of the Java Serializable InterfaceImplementation of the Java Serializable Interface
An Object is Serializable only if its Class An Object is Serializable only if its Class Implements the Serializable InterfaceImplements the Serializable Interface Serialization Utilizes Exception Handling For Example, writeObject Method Throws a
NotSerializableException if the given Object is not serializable
Serializable is an Empty InterfaceSerializable is an Empty Interface Does not Contain Any Method Declarations Identifies Classes whose Objects are
Serializable
CSE333
Java-1.99
Implementing the Serializable InterfaceImplementing the Serializable Interface
The Serializable InterfaceThe Serializable Interface public interface Serializable
{ // there's nothing in here!}; To make Instances of a Vlass serializable, add the To make Instances of a Vlass serializable, add the
Implements Serializable to Class Defenition Implements Serializable to Class Defenition public class MySerializableClass implements
Serializable { … } User does not have to Write any Methods
Serialization of Objects are Handled by the Serialization of Objects are Handled by the defaultWriteObject Method of the defaultWriteObject Method of the ObjectOutputStream ObjectOutputStream
CSE333
Java-1.100
defaultWriteObject MethoddefaultWriteObject Method
The defaultWriteObject Method is Defined in The defaultWriteObject Method is Defined in ObjectOutputStream ClassObjectOutputStream Class
defaultWriteObject Writes all Necessary Details to defaultWriteObject Writes all Necessary Details to Reconstruct an Instance of the ClassReconstruct an Instance of the Class Class of the Object Class Signature Values of Non-Transient and Non-Static
Members Including References to Other Contained Objects
In Turn, Contained Objects, their Classes, Signatures, Values, etc., are also Written
Process Continues in a Logically Recursive Fashion