The Java Language and Environment - PowerPoint PPT Presentation

About This Presentation
Title:

The Java Language and Environment

Description:

Title: No Slide Title Author: Alex Last modified by: Steven A. Demurjian Created Date: 11/12/1997 7:36:58 AM Document presentation format: On-screen Show – PowerPoint PPT presentation

Number of Views:350
Avg rating:3.0/5.0
Slides: 101
Provided by: alex57
Category:

less

Transcript and Presenter's Notes

Title: The Java Language and Environment


1
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
steve_at_engr.uconn.edu http//www.engr.uconn.edu/st
eve http//www.engr.uconn.edu/cse (860) 486 - 4818
2
Overview of Presentation
  • Motivation and Introduction to Java
  • Designing and Developing Applets in Java
  • The Java User Interface - GUI with AWT
  • Designing and Developing Java Classes
  • Inheritance and Interfaces in Java
  • Polymorphism and Object Serialization

3
Motivation and Introduction to Java
  • Java is Emerging as the OO Language of Choice
  • Javas Utilization in
  • Distributed Internet-Based Applications of All
    Types
  • Legacy/COTS Integration for Enterprise Computing
  • General-Purpose, Single-CPU Development
  • Significant Dissemination on WWW
  • http//www.javasoft.com
  • http//www.gamelan.com
  • Well Overview Key Features and Capabilities

4
An Overview of Java
  • Java is a Third Generation, General Purpose,
    Platform Independent, Concurrent, Class-Based,
    Object-Oriented Language and Environment
  • Java Composed of JDK and JRE
  • Java Language
  • Java Packages (Libraries)
  • javac Compiler to Bytecode (p-code)
  • JDB Java Debugger
  • Java Interpreter - Platform Specific
  • JDK Java Development Environment
    http//www.javasoft.com/products/jdk/1.2/
  • JRE Java Runtime Environment http//www.javasoft.
    com/products/jdk/1.2/jre/index.html

5
What is Java?Software Releases and IDEs
  • Java is Free!
  • Current Releases
  • Version 2 for Win95, Win98, NT
  • Version 2 (Early Access) for Solaris
  • Third-Party Ports to All Conceivable HW/SW
    Platforms from Micros to Mainframes
    http//www.javasoft.com/cgi-bin/java-ports.cgi
  • Integrated Development Environments (IDEs)
  • Commercial Products, Freeware, Visual IDEs
  • Visual J, Visual Café, Kawa, Jpad, Javelin

6
Java Virtual Machine (JVM)
  • JVM is a Platform Specific Program which
    Interprets and Executes Java Code
  • JVM Interprets and Executes Bytecodes
  • JVM Targeted as Small/Efficient - Embeddable
    within Consumer Electronics
  • JVM Stack Based Machine - Simulates Real Processor

CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01
08 00 20 08

7
Java Visualization
8
Packages In Java
  • Allows Related Classes to be Grouped into a
    Larger Abstraction
  • Similar to Ada95 Packages
  • Unavailable in C
  • Utilization of Packages for SW Design and
    Development
  • Components, Modularization, Groupings
  • Enforcement by Compiler of Package Rules
  • Overall, Packages Enhance the Control and
    Visibility to Fine-Tune
  • Who Can See What When

9
The Java API Packages
  • Application Programming Interface (API)
  • Java Defined - Building Blocks/Libraries
  • Java Platform 1.2/2 Core API
  • java.applet java.rmi
  • java.awt java.rmi.dgc
  • java.awt.datatransfer java.rmi.registry
  • java.awt.event java.rmi.server
  • java.awt.image java.security
  • java.beans java.security.acl
  • java.io java.security.interfaces
  • java.lang java.sql
  • java.lang.reflect java.text
  • java.math java.util
  • java.net java.util.zip
  • Power of Java Contained with APIs

10
The Java Language
  • Overview 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 Java
  • Primitive Types ints, floats, booleans, Unicode
    chars
  • Reference Types arrays, classes, interfaces
  • No Physical Pointers in Java!

11
The Java Language
  • Statements in Java - Resembles C and C
  • Assignment/Expressions and Precedence
  • for, while, do-while
  • if-then, switch-case
  • break, continue, label, return
  • Exception Handling
  • Similar to C
  • try, throws, catch Blocks
  • Strongly Integrated Throughout APIs

12
The Java LanguageMotivating the Class Concept
  • Conceptually, Classes are Structures/Records with
    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)
13
The Java LanguageObject-Oriented Features
  • Class - similar to C Class
  • Classes have Members (Methods and Variables)
  • Members Tagged Using Keywords
  • private Typically, Inaccessible
  • public Potential to be Accessible
  • protected Accessible via Inheritance
  • package Accessible within Package
  • Involve Visible Between Classes, Within Packages,
    and Due to Inheritance

14
Classes in Java
  • A Supermarket Item
  • Keywords must be Utilized for Each Attribute or
    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
15
Classes 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 gt 0)
Quantity Delta return
true else return
false public int Get_InStock_Amt()
return Quantity public double
Compute_Item_Profit() ... protected boolean
Modify_WholeSale() ...
16
Visibility of Attributes/Methods
  • Class Members (Attributes and Methods)
  • Visibility 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
    not Supported in C
  • Abstraction/Encapsulation Superior in Java!

17
Inheritance - Two Roles
  • Controlled Sharing Between Classes
  • Generalization vs. Specialization
  • Treat Instances of Different Classes in a
    Uniform Fashion
  • Polymorphism and Dynamic Binding
  • Inheritance in Java

Item / \
DeliItem ProduceItem SaladItem
class DeliItem extends Item ...
class SaladItem extends DeliItem ...
class
ProduceItem extends Item ...
18
Designing and Developing Applets in Java
  • Applets Small Independent Programs Intended for
    Embedding into WWW Pages and Executable via
    Java-Enabled Browser (Netscape or IE)
  • Applets Operate Under Severe Security Limits
  • Cant Execute Local Programs
  • Cant Communicate with Host Other than one from
    Which Downloaded
  • Cant Read/Write to Local File System
  • Cant Find Information on Local System Except
    Java/OS Versions and Character/Line Separators

19
Designing and Developing Applets in Java
  • An Applet is a Java Program that Executes as part
    of an HTML Page

applet A.java
HTML file ... ltAPPLET CODE A.classgt ...
javac
applet A.class
20
Applets Inheritance Structure
Everything in Java inherits from the Object class
  • java.lang.Object
  • java.awt.Component
  • java.awt.Container
  • java.applet.Applet
  • your applet

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.
21
Applet Methods Eligible for Overriding
  • Methods for Milestones
  • init - initializes an applet when it is loaded
  • start - (re)starts applets execution
  • stop - stops applets execution
  • destroy - final cleanup before unloading
  • Methods for Drawing
  • paint
  • update

The applet subclass must override at least one of
these methods init, start or paint.
22
Handling Events
  • Applets Handle Events by Implementing the
    Corresponding interface

mouseClicked mouseEntered mouseExited mousePressed
mouseReleased
  • import java.awt.event.MouseListener
  • import java.awt.event.MouseEvent
  • public class Simple extends Applet
  • implements MouseListener
  • public void init()
  • addMouseListener(this)
  • public void mouseClicked(MouseEvent event)
  • addItem(click)

Protocol of behavior
All methods in the interface must be implemented
23
Running an Applet in HTML
  • ltAPPLET CODE AppletSubclass.class WIDTH
    anInt HEIGHT anIntgt
  • lt/APPLETgt
  • The Browser
  • Reserves a Display Area for the Applet
  • Loads the bytecode
  • Creates an Instance of the Subclass
  • Calls the init and start Methods

24
Loading an Applet
  • Finding an Applet
  • CODEBASE
  • Relative/Absolute Address
  • CODEBASEexample/
  • CODEBASEhttp//someServer//otherDirectory/
  • Bringing the Applet
  • Class by Class/Archives

otherDirectory
example
HTML file
HTML file
Class file
Class file
25
The ltAPPLETgt tag
  • ltAPPLET
  • CODEBASE codebaseURL
  • (CODE appletFile OBJECT serializedApplet)
  • ARCHIVE archivesList
  • ALT alternateText
  • NAME appletInstanceName
  • WIDTH pixels HEIGHT pixels
  • ALIGN alignment
  • VSPACE pixels HSPACE pixels
  • gt
  • ltPARAM NAME appletParameter1 VALUE valuegt
  • ltPARAM NAME appletParameter2 VALUE valuegt
  • alternateHTML
  • lt/APPLETgt

26
Security Issues
  • 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

27
Example of a GUI Applet
  • / http//java.sun.com/docs/books/tutorial/ui/comp
    onents/example/
  • ButtonDemo.java /
  • import java.awt.
  • import java.awt.event.ActionListener
  • import java.awt.event.ActionEvent
  • import java.applet.Applet
  • public class ButtonDemo extends Applet
  • implements ActionListener
  • Button b1, b2, b3
  • static final String DISABLE "disable"
  • static final String ENABLE "enable"
  • public void init()
  • b1 new Button()
  • b1.setLabel("Disable middle button")
  • b1.setActionCommand(DISABLE)

28
Example of a GUI Applet (Continued)
  • //Listen for actions on buttons 1 and 3.
  • b1.addActionListener(this)
  • b3.addActionListener(this)
  • //Add Components to the Applet, using the
    default FlowLayout.
  • add(b1)
  • add(b2)
  • add(b3)
  • public void actionPerformed(ActionEvent e)
  • String command e.getActionCommand()
  • if (command DISABLE) //They clicked
    "Disable middle button"
  • b2.setEnabled(false)
  • b1.setEnabled(false)
  • b3.setEnabled(true)
  • else //They clicked "Enable middle
    button"
  • b2.setEnabled(true)

29
The Java User Interface - GUI with AWT
  • UI Refers to the Communications Between a Program
    and a User
  • Java Abstract Windowing Toolkit (AWT) and Swing
    Contains Complete Set of Classes for Writing GUI
    Programs
  • AWT Classes Categorized into
  • GUI Components
  • Containers
  • Layout Managers
  • Drawing
  • Event Handling

30
AWT Components
  • Button
  • CheckBoxes
  • Choices
  • Lists
  • Menus
  • Textfields
  • Text Areas
  • Labels

31
Containers
  • The Java AWT Provides Three Types of Containers
    Implemented as Subclasses of 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

32
Inheritance Hierarchies for Components
33
Layout Managers
  • Layout Manager Controls the Size and Position of
    Components in a Container
  • By Default Every Container Object has an
    Associated LayoutManger
  • Panel Objects - FlowLayout
  • Window Object - BorderLayout

34
Layout Managers - Simple
  • FlowLayout
  • Default for Panel Objects
  • Lays out Components from Left to Right Starting
    New Rows if Needed
  • GridLayout
  • Displays the Components in Equal Size in the
    Requested Number of Rows and Columns

35
Layout Managers - Special Purpose
  • BorderLayout
  • Default for Window Objects
  • Uses 5 Areas to hold Components North, South,
    East, West, and Center
  • CardLayout
  • One Area Contains Different Components at
    Different Times

36
Layout Managers - Flexible
  • GridBagLayout
  • 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

37
Example of a GUI applet
TextField
Name
TextArea
Address
Order Now
Label
CheckBox
Size
Choices
Color
OK
Cancel
Quit
Button
38
Excerpts for GUI Applet Example(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
39
Excerpts for GUI Applet Example (Note Many
Lines Omitted!!)
p1.setLayout(new GridLayout(0,2,2,2)) p1.ad
d(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.ad
d(quit) setLayout(new BorderLayout()) add(
"North", p1) add("South", p2)
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")
40
Excerpts for GUI Applet Example (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.targe
t 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
41
Event Handling
  • When a User Acts on a Component, the AWT Detects
    the Event and Notifies the Event Listeners
  • A Class Implements the Event Listener and Every
    Class Instance can Register as Event Listeners
  • 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

42
Example of Event Handling
  • public class Beeper ... implements ActionListener
  • ...
  • // where initialization occurs
  • button.addActionListener(this)
  • ...
  • public void actionPerformed(ActionEvent e)
  • // Make a beep sound
  • ...

43
The AWT Events
  • Action Events
  • Adjustment Event
  • Component Events
  • Container Events
  • Focus Events
  • Item Events
  • Key Events
  • Mouse Events
  • Mouse-Motion Events
  • Text Events
  • Window Event

44
Action Listeners
  • Easiest Event Handlers to Implement
  • Generated by
  • Clicking a Button
  • Double Clicking a List Item
  • Choosing a Menu Item
  • Pressing Return in a Text Field
  • Listener Interface - ActionListener
  • Methods - actionPerformed(ActionEvent)

45
Action Listeners - ActionEvent
  • Parameter to the actionPerfomed Method
  • ActionEvent Defines Two Useful Methods
  • String setActionCommand
  • Associates a string to the action
  • String getActionCommand
  • Returns the string associated with this action

46
Item Listeners
  • Generated by Components that Maintain State,
    Generally on/off State
  • Components that Generate ItemEvents
  • Checkboxes
  • Choices
  • Lists
  • Listener Interface - ItemListener
  • Methods - itemStateChanged(ItemEvent)

47
ItemListeners - ItemEvent
  • Parameter to the itemStateChanged Method
  • 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

48
Excerpts for GUI Applet with Listener(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)
49
Excerpts for GUI Applet with Listener(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
50
Designing and Developing Java Classes
  • Encapsulation Capabilities of Java
  • Classes (Data Operations) - ADTs
  • Packages - Collections of Related Classes
  • Class Declaration
  • Access Modes and Variable Members
  • Constructors and Class Bodies
  • Method Declaration and Access Modes
  • Class and Instance Members
  • Garbage Collection

51
Class Definition
Class Declaration
  • public class Stack
  • private Vector items
  • public Stack()
  • items new Vector(10)
  • public Stack(int numElem)
  • items new Vector(numElem)
  • public Object push(Object item)
  • item.addElement(item)
  • return item
  • public synchronized Object pop()
  • int len items.size()
  • Object obj null
  • if (len 0)
  • throw new EmptyStackException()
  • obj items.elementAt(len - 1)
  • items.removeElementAt(len - 1)

Member Variable
Constructors
Class Body
Member Methods
52
Packages
  • A package is a Collection of Related Classes and
    Interfaces that Provides Access Protection and
    Namespace Management
  • File Name and Package Name Identical
  • Packages are Imported via the import Keyword
  • package graphics
  • class Circle extend Graphic implements Draggable
  • ...
  • class Rectangle extends Graphic implements
    Draggable
  • ...
  • interface Draggable
  • ...

53
Access Modes
  • Constructors and Members 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 and Allows Evolvability
    with Minimal Impact on other Classes that use the
    Members
  • Deciding Appropriate Access Mode Determines
    Security and Ensures that Data Remains in a
    Consistent State.

54
Constructors
  • Utilized to Create a new Class instance by
    Reserving Sspace for the Member Variables
    Rectangle rect new Rectangle()Member Variable
    Initialization Possible
  • Constructors Mimic Class Name with No Return Type
  • Default Constructor with Empty Argument List
  • Constructors may be Overloaded

55
Variable Members
  • Declaration (Class Body)
  • Defines the Type of a Variable
  • Instantiation (Constructor)
  • Reserves Memory for the New Instance
  • Initialization
  • Assign Initial Value(s)

56
Method Members
  • Declaration
  • 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

57
Method Members (cont.)
58
Example
  • public class Point
  • public int x 0
  • public int y 0
  • public void move(int newX, int newY)
  • x newX
  • y newY
  • public class Line
  • public Point origin
  • public Point end
  • public Line()
  • origin new Point()
  • end new Point()
  • public Line(Point origin, Point end)

aLineObject
Default Constructor
Line Instance
origin
end
x y
x y
Point Instances
Overloading
Hiding
59
Class and Instance Members
  • Class Members are Defined with the Keyword static
  • Class Variables and Class Methods are Associated
    with the Class Rather than each of its Instances
  • Class Variables are Shared Among all Instances
  • JRE Creates one copy of Class Variables the First
    Time it Encounters a Containing Instance
  • Class Methods only Operate on Class Variables
  • Class Bariables declared as final are constants
  • Class Members are Accessible without the need to
    Instantiate the Class
  • className.classMethod()
  • className.classVar 10

60
Class and Instance Members (Continued)
  • class AnInteger
  • int x
  • public int x()
  • return x
  • public void setX(int newX)
  • x newX

class AnInteger int x static public int
x() return x static 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())
61
Garbage Collection
  • Unreferenced Objects are Garbage Collected
    Automatically
  • Memory is Freed for Later Reuse
  • Garbage Collection runs in a Low Priority Thread,
    either Synchronously or Asynchronously
  • The finalize() Method is Inherited from Object
    and can be Overridden to Liberate Resources

62
Inheritance in Java
  • Basic Definitions and Concepts
  • Generalization vs. Specialization
  • Subclass vs. Superclass
  • 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 Classes
  • Java Interfaces for Design-Level Multiple
    Inheritance and Quasi Generics

63
Inheritance - Terms and Concepts
  • Every Class in Java is Derived from the Object
    Class
  • Java Classes can be Organized into Hierarchies
    Using the extends Keyword
  • Establishing Superclass/Subclass Relationships
    Between the Classes in Application
  • A Superclass Contains Members Common to Its
    Subclasses - Generalization
  • Subclasses Contain Members Different from Shared
    Superclass - Specialization
  • Only Single Inheritance is Supported in Java at
    Implementation Level!

64
Subclass Superclass
  • 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 or hide the Inherited Member
    Variables and Override the Inherited Member
    Functions
  • Superclass
  • Superclass is a Classs Direct Ancestor

65
A Superclass in Java
  • A Supermarket Item
  • Keywords must be Utilized for Each Attribute or
    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
66
Inheritance - Defining Subclasses in Java
  • Item
  • / \
  • DeliItem ProduceItem
  • SaladItem

class DeliItem extends Item ...
class SaladItem extends DeliItem ...
class
ProduceItem extends Item ...
67
Members Inherited By a Subclass
  • Subclass Inherits all Public/Protected Members of
    a Superclass
  • DeliItem Inherits Public/Protected from Item
  • Subclass Inherits all Package Members of Classes
    in the same Package as the Subclass
  • All superclass Members can be Declared with no
    Access Specification, if Subclass is in the Same
    Package as the Superclass

68
Members Not Inherited By A Subclass
  • Subclass does not Inherit Private Members of a
    Superclass
  • DeliItem doesnt Inherit Private from Item
  • Subclasses do not Inherit a Superclasss Member
    if the 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

69
Hiding Member Variables and 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)

70
Overriding Member Methods
  • Subclasses CANNOT Override Methods that are
    Declared to be Final in the Superclass
  • Subclasses MUST Override Methods that are
    Declared as Abstract in the Superclass
  • Subclasses MUST be Declared as Abstract if they
    do not Override Abstract Methods from the
    Superclass

71
Methods Inherited From Object Class
  • The Java Object Class Defines Basic State and
    Behavior of all Classes and Their Instances
  • User Defined Classes can Override these Methods
  • clone
  • equals
  • finalize
  • toString
  • hashCode
  • User Defined Classes Cannot Override
  • getClass
  • notify
  • notifyAll
  • wait

72
Public, Final, and Abstract Classes
  • Public Classes
  • Within Package, public Classes Become Visible to
    Outside World
  • Public Members are Exported
  • Final Classes
  • Prohibits Subclassing for Security
  • Final Class Prevents Access of Protected Members
    via Subclassing
  • Not Supported in C/Ada95
  • Abstract Classes
  • Can't be Instantiated
  • No Implementations for Abstract Methods

73
Final Classes and the Final Keyword
  • A Class is Declared as Final - the Class Cannot
    be Subclassed.
  • For Security
  • For Design
  • A Method is Declared as Final in a Class - any
    Subclass Cannot Override that Method
  • A Variable is Declared as Final - the Variable is
    a Constant and it Cannot be Changed

74
Abstract Classes And Methods
  • Abstract 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 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

75
A 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(dou
ble NewPrice)...
76
Another 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() . . . . .

77
Interfaces in Java
  • Design-Level Multiple Inheritance
  • Java Interface
  • Set of Methods (no Implementations)
  • Set (Possibly Empty) of Constant Values
  • Interfaces Utilized Extensively Throughout Java
    APIs 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

78
A 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
79
Quasi Generics in Java
class Set implements Coll void add(Object
obj) ... void delete(Object obj)
...
interface Coll int MAXIMUM 500 void
add(Object obj) void delete(Object obj)
Object find(Object obj) int currentCount()
class Queue implements Coll void add(Object
obj) ... void delete(Object obj) ...
80
Polymorphism and Object Serialization in Java
  • Polymorphism
  • 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!
  • Serialization
  • Conversion of Object to Format that Facilitates
    Storage to File or Transfer Across Network
  • Process Controlled via API with Minimal
    Interaction by Software Engineer

81
Polymorphism
  • Substitutability
  • 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 Type
  • Type Defined in the Variable Declaration
  • Dynamic Type
  • Type of the Actual Value held by the Variable at
    Runtime

82
Polymorphism
  • A Variable is Polymorphic Whenever it may have
    Different 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
  • 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?

83
An Example
  • We have a class Ball, and two subclasses
    WhiteBall and BlackBall
  • The SelectOne() method gets a WhiteBall and a
    BlackBall as arguments and returns one of them
    selected randomly
  • Questions
  • What is SelectOne()s return type?
  • How can we know which ball was returned?

SelectOne
?
84
Dynamic Binding and Casting
The static type of b is Ball, but its dynamic
type is either WhiteBall or BlackBall.
  • public 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()
  • class balls
  • public static void main(String args)
  • WhiteBall wb new WhiteBall()
  • BlackBall bb new BlackBall()
  • Ball b SelectOne(wb, bb)
  • System.out.println(b.GetId())
  • System.out.println(b.id)
  • if (b instanceof WhiteBall)
  • wb (WhiteBall)b
  • wb.OnlyWhite()
  • else
  • bb (BlackBall)b
  • bb.OnlyBlack()
  • public static Ball SelectOne(WhiteBall w,
    BlackBall b)
  • if (Math.random() gt 0.5)
  • return w
  • else

What is going to be printed?
85
Class Student (Superclass) - Maintains Student
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)

86
Class 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)

87
Class 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)

88
Class 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 lt DBSize)(found false))
  • stu (Student) stuList.elementAt(count)
  • if (stu.getName().equals(name))
  • found true
  • count
  • return stu

89
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 lt 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 lt DBSize i)
  • Student stu (Student) stuList.elementAt(i)
  • stu.print()
  • System.out.println()

90
Class 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 gt 0 option lt 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 ")

91
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)

92
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

93
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()

94
Object Serialization
  • Object Serialization is the Process of Reading
    and Writing Objects
  • Bi-directional Process of Write (Save in
    Serialized form) and Read (Reconstruct from
    Serialized form)
  • ObjectInputStream and ObjectOutputStream are used
    for Reading and Writing Objects
  • 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

95
Using Object Serialization
  • Straightforward Process in Java
  • Serialize Objects by ...
  • Writing Objects to an ObjectOutputStream
  • Deserialize Objects by ...
  • Reading Objects using ObjectInputStream
  • Design/Develop Classes that Promote the
    Serialization/Deserialization of Instances
  • 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

96
Writing to an ObjectOutputStream
  • The Following Code Segment Serializes the Date
    Object
  • FileOutputStream out new FileOutputStream("th
    eTime")
  • ObjectOutputStream s new ObjectOutputStream(o
    ut)
  • s.writeObject("Today")
  • s.writeObject(new Date())
  • s.flush()
  • Serializes the Object to a File named theTime

97
Reading From an ObjectInputStream
  • The Following Code Segment Reconstructs by
    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
    the File theTime
  • If Multiple Independent Objects were Written,
    Objects must be Read in the Same Order
  • Return Value from readObject has to be Cast to a
    Specific Type

98
Utilizing Object Serialization
  • Serialization/Deserialization Occurs via the
    Implementation of the Java Serializable Interface
  • An Object is Serializable only if its Class
    Implements 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 Interface
  • Does not Contain Any Method Declarations
  • Identifies Classes whose Objects are Serializable

99
Implementing the Serializable Interface
  • The Serializable Interface
  • public interface Serializable // there's
    nothing in here!
  • To make Instances of a Vlass serializable, add
    the 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
    defaultWriteObject Method of the
    ObjectOutputStream

100
defaultWriteObject Method
  • The defaultWriteObject Method is Defined in
    ObjectOutputStream Class
  • defaultWriteObject Writes all Necessary Details
    to Reconstruct 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
Write a Comment
User Comments (0)
About PowerShow.com