Chapter 9: Objectoriented Programming - PowerPoint PPT Presentation

1 / 63
About This Presentation
Title:

Chapter 9: Objectoriented Programming

Description:

Use downcasting (casting a superclass reference to a ... pointing to a Circle object, so it calls method toString of class Circle. ... – PowerPoint PPT presentation

Number of Views:55
Avg rating:3.0/5.0
Slides: 64
Provided by: jayrobertc
Category:

less

Transcript and Presenter's Notes

Title: Chapter 9: Objectoriented Programming


1
Xavier University Computer Center Sun
Microsystems, Philippines
Java sa Eskwela (JsE) Program
2
Chapter 9
Object-oriented Programming
3
Chapter 9
  • Outline
  • Superclasses and Subclasses
  • protected Members
  • Relationship between Superclass Objects and
    Subclass Objects
  • Constructors and Finalizers in Subclasses
  • Implicit Subclass-Object-to-Superclass-Object
    Conversion
  • Software Engineering with Inheritance
  • Composition vs. Inheritance
  • Introduction to Polymorphism
  • Type Fields and switch Statements
  • Dynamic Method Binding

4
Chapter 9
  • Outline
  • final Methods and Classes
  • abstract Superclasses and Concrete Classes
  • Polymorphism Examples
  • New Classes and Dynamic Binding

5
Objectives
  • To understand inheritance and software
    reusability
  • To understand superclasses and subclasses
  • To appreciate how polymorphism makes systems
    extensible and maintainable

6
Objectives
  • To understand the distinction between abstract
    classes and concrete classes
  • To learn how to create abstract classes and
    interfaces

7
OO Programming
  • Inheritance form of software reusability
  • new classes created from existing ones
  • absorb attributes and behaviors, and add in their
    own
  • override methods redefine inherited methods
  • subclass inherits from superclass
  • direct superclass subclass explicitly inherits
  • indirect superclass subclass inherits from two
    or more levels up the class hierarchy

8
OO Programming
  • Inheritance example
  • a rectangle "is a" quadrilateral
  • rectangle is a specific type of quadrilateral
  • quadrilateral is the superclass, rectangle is the
    subclass
  • incorrect to say quadrilateral "is a" rectangle
  • subclass more specific than superclass

9
OO Programming
Shape
TwoDimensionalShape
ThreeDimensionalShape
Circle
Square
Sphere
Cube
10
OO Programming
class Animal
eat( ) sleep( ) reproduce( )
Cat Simon
eat() reproduce() sleep() huntmice() purr()
class Mammal
reproduce( )
class Cat
sleep( ) huntmice( ) purr( )
11
OO Programming
  • Using inheritance
  • use keyword extends
  • class TwoDimensionalShape extends Shape
  • private members of superclass not directly
    accessible to subclass
  • all other variables keep their member access

12
OO Programming
  • In a superclass
  • public members
  • accessible anywhere program has a reference to a
    superclass or subclass type
  • private members
  • accesible only in methods of the superclass
  • protected members
  • intermediate protection between private and
    public
  • only accessible by methods of superclass, of
    subclass, or classes in the same package

13
OO Programming
  • subclass methods
  • can refer to public or protected members by name
  • overridden methods accessible with
    super.methodName

14
OO Programming
  • Relationship between Superclass Objects and
    Subclass Objects
  • object of subclass
  • can be treated as object of superclass
  • reverse not true
  • suppose many classes inherit from one superclass
  • can make an array of superclass references
  • treat all objects like superclass objects

15
OO Programming
  • Relationship between Superclass Objects and
    Subclass Objects
  • explicit cast
  • convert superclass reference to a subclass
    reference (downcasting)
  • can only be done when superclass reference
    actually referring to a subclass object
  • instanceof operator
  • if (p instanceof Circle)
  • returns true if the object to which p points "is
    a" Circle

16
OO Programming
  • Relationship between Superclass Objects and
    Subclass Objects
  • overridding methods
  • subclass can redefine superclass methods
  • when method mentioned in subclass, subclass
    version used
  • access original superclass method with
    super.methodName
  • to invoke superclass constructor explicitly
  • super() //can pass arguments if needed
  • if called explicitly, must be first statement

17
OO Programming
  • Constructors in Subclasses
  • Objects of subclass
  • superclass constructor should be called
  • initialize superclass variables
  • default constructor called implicitly
  • explicit call (using super) must first command

18
OO Programming
  • Example
  • public class Circle extends Point
  • Circle(double r, int a, int b)
  • super(a,b)
  • radius r

19
// Fig. 9.4 Point.java // Definition of class
Point public class Point protected int x,
y // coordinates of the Point // No-argument
constructor public Point() //
implicit call to superclass constructor occurs
here setPoint( 0, 0 ) //
Constructor public Point( int a, int b )
// implicit call to superclass constructor
occurs here setPoint( a, b )
20
// Set x and y coordinates of Point public
void setPoint( int a, int b ) x a
y b // get x coordinate public
int getX() return x // get y
coordinate public int getY() return y
// convert the point into a String
representation public String toString()
return "" x ", " y ""
21
// Fig. 9.4 Circle.java // Definition of class
Circle public class Circle extends Point //
inherits from Point protected double radius
// No-argument constructor public Circle()
// implicit call to superclass
constructor occurs here setRadius( 0 )
// Constructor public Circle( double r,
int a, int b ) super( a, b ) // call
to superclass constructor setRadius( r )

22
// Set radius of Circle public void
setRadius( double r ) radius ( r gt
0.0 ? r 0.0 ) // Get radius of Circle
public double getRadius() return radius
// Calculate area of Circle public
double area() return Math.PI radius
radius // convert the Circle to a
String public String toString()
return "Center " "" x ", " y ""
" Radius " radius
23
// Fig. 9.4 InheritanceTest.java //
Demonstrating the "is a" relationship import
java.text.DecimalFormat import
java.swing.JOptionPane public class
InheritanceTest public static void main(
String args ) Point pointRef, p
Circle circleRef, c String output
p new Point( 30, 50 ) c new Circle(
2.7, 120, 89 ) output "Point p "
p.toString() "\nCircle c " c.toString()
// use the "is a" relationship to refer to a
Circle // with a Point reference
pointRef c // assign Circle to pointRef
24
output "\n\nCircle c (via pointRef) "
pointRef.toString() // Use downcasting
(casting a superclass reference to a //
subclass data type) to assign pointRef to
circleRef circleRef (Circle) pointRef
output "\n\nCircle c (via circleRef) "
circleRef.toString() DecimalFormat
precision2 new DecimalFormat( "0.00" )
output "\nArea of c (via circleRef) "
precision2.format( circleRef.area()
) // Attempt to refer to Point object
// with Circle reference if ( p
instanceof Circle ) circleRef
(Circle) p // line 40 in Test.java
output "\n\ncast successful"
else output "\n\np does not refer to
a Circle"
25
JOptionPane.showMessageDialog( null,
output, "Demonstrating the \"is a\"
relationship", JOptionPane.INFORMATION_ME
SSAGE ) System.exit( 0 )
26
OO Programming
  • Finalizers in Subclasses
  • if method finalize defined
  • subclass finalize should call superclass finalize
    as last action
  • should be protected
  • only subclasses have access

27
OO Programming
  • Example
  • public class Circle extends Point
  • protected void finalize()
  • super.finalize()

28
OO Programming
  • References to subclass objects
  • may be implicitly converted to superclass
    references
  • makes sense - subclass contains members
    corresponding to those of superclass
  • referring to a subclass object with a superclass
    reference
  • allowed - a subclass object "is a" superclass
    object
  • can only refer to superclass members

29
OO Programming
  • References to subclass objects
  • referring to a superclass object with a subclass
    reference
  • error
  • must first be cast to a superclass reference
  • need way to use superclass references but call
    subclass methods
  • discussed later in the chapter

30
OO Programming
  • Inheritance Example
  • Class Point
  • protected variables x, y
  • Methods setPoint, getX, getY, toString
  • Class Circle (extends Point)
  • protected variable radius
  • Methods setRadius, getRadius, area, override
    toString
  • Class Cylinder (extends Circle)
  • protected variable height
  • Methods setHeight, getHeight, area (surface
    area), volume, override toString

31
// Fig. 9.8 Cylinder.java // Definition of class
Cylinder public class Cylinder extends Circle
protected double height // height of
Cylinder // No-argument constructor
public Cylinder() // implicit call to
superclass constructor here setHeight( 0
) // constructor public Cylinder(
double h, double r, int a, int b )
super( r, a, b ) setHeight( h )
// Set height of Cylinder public void
setHeight( double h ) height ( h gt
0 ? h 0 )
32
// Get height of Cylinder public double
getHeight() return height //
Calculate area of Cylinder (i.e., surface area)
public double area() return 2
super.area() 2 Math.PI radius
height // Calculate volume of
Cylinder public double volume()
return super.area() height //
Convert the Cylinder to a String public String
toString() return super.toString() "
Height " height
33
// Fig. 9.8 Test.java // Application to test
class Cylinder import javax.swing.JOptionPane imp
ort java.text.DecimalFormat public class Test
public static void main( String args )
Cylinder c new Cylinder( 5.7, 2.5, 12, 23
) DecimalFormat precision2 new
DecimalFormat( "0.00" ) String output
output "X coordinate is " c.getX()
"\nY coordinate is " c.getY()
"\nRadius is " c.getRadius()
"\nHeight is " c.getHeight()
34
c.setHeight( 10 ) c.setRadius( 4.25
) c.setPoint( 2, 2 ) output
"\n\nThe new location, radius "
"and height of c are\n" c "\nArea is
" precision2.format( c.area() )
"\nVolume is " precision2.format( c.volume()
) JOptionPane.showMessageDialog( null,
output, "Demonstrating Class Cylinder",
JOptionPane.INFORMATION_MESSAGE )
System.exit( 0 )
35
(No Transcript)
36
OO Programming
  • Declaring variables final
  • indicates they cannot be modified after
    declaration
  • must be initialized when declared
  • Declaring methods final
  • cannot be overridden in a subclass
  • static and private methods are implicitly final
  • program can inline final methods
  • actually inserts method code at method call
    locations
  • improves program performance

37
OO Programming
  • Declaring classes final
  • cannot be a superclass (cannot inherit from it)
  • all methods in class are implicitly final

38
OO Programming
  • Abstract classes (abstract superclasses)
  • sole purpose is to be a superclass
  • other classes inherit from it
  • cannot instantiate objects of an abstract class
  • can still have instance variables and
    constructors
  • too generic to define real objects
  • declare class with keyword abstract

39
OO Programming
  • Concrete class
  • can instantiate objects
  • provide specifics
  • Class hierarchies
  • most general classes are usually abstract
  • TwoDimensionalShape too generic to be concrete

40
OO Programming
  • Polymorphism Examples
  • Class Quadrilateral
  • Rectangle "is a" Quadrilateral
  • getPerimeter method can be performed on any
    subclass
  • square, Parallelogram, Trapezoid
  • same method takes on "many forms" - polymorphism

41
OO Programming
  • Polymorphism Examples
  • Class Quadrilateral (cont.)
  • have an array of superclass references
  • array would point to all the objects
  • call getPerimeter using the references
  • appropriate method called for each class

42
OO Programming
  • Polymorphism Examples
  • adding a new subclass
  • simply need to define getPerimeter for that class
  • can refer to it with superclass reference
  • can use same superclass array as before - "fits
    right in"

43
OO Programming
  • With Polymorphism
  • new classes can be added easily
  • one method call can cause different actions to
    occur, depending on object recieving call

44
OO Programming
  • Polymorphism Example program
  • abstract superclass Employee
  • abstract method earnings
  • Must be implemented in each subclass
  • Classes Boss, CommissionWorker, and PieceWorker,
    HourlyWorker
  • Override methods toString and earnings
  • Class Test
  • Initialize objects
  • Use an Employee reference and call toString and
    earnings
  • Through polymorphism, the appropriate class
    method is called

45
// Fig. 9.9 Employee.java // Abstract base class
Employee public abstract class Employee
private String firstName private String
lastName public Employee( String first,
String last ) firstName first
lastName last public String
getFirstName() return firstName public
String getLastName() return lastName
public String toString() return firstName '
' lastName // Abstract method that must
be implemented for each derived class of //
Employee from which objects are instantiated.
public abstract double earnings( )
46
// Fig. 9.9 Boss.java // Boss class derived from
Employee public final class Boss extends Employee
private double weeklySalary public
Boss( String first, String last, double s)
super( first, last ) // call superclass
constructor setWeeklySalary( s )
public void setWeeklySalary( double s )
weeklySalary ( s gt 0 ? s 0 )
public double earnings() return
weeklySalary public String
toString() return "Boss "
super.toString()
47
// Fig. 9.9 CommissionWorker.java //
CommissionWorker class derived from
Employee public final class CommissionWorker
extends Employee private double salary
// base salary per week private double
commission // amount per item sold private
int quantity // total items sold for
week public CommissionWorker( String first,
String last, double
s, double c, int q) super( first, last )
// call superclass constructor setSalary(
s ) setCommission( c ) setQuantity(
q ) public void setSalary( double s
) salary ( s gt 0 ? s 0 )
48
public void setCommission( double c )
commission ( c gt 0 ? c 0 )
public void setQuantity( int q )
quantity ( q gt 0 ? q 0 )
public double earnings() return salary
commission quantity public String
toString() return "Commission worker "
super.toString()
49
// Fig. 9.9 PieceWorker.java // PieceWorker
class derived from Employee public final class
PieceWorker extends Employee private double
wagePerPiece // wage per piece output private
int quantity // output for week
public PieceWorker( String first, String last,
double w, int q ) super( first, last )
// call superclass constructor setWage( w
) setQuantity( q ) public
void setWage( double w ) wagePerPiece
( w gt 0 ? w 0 ) public void
setQuantity( int q ) quantity ( q gt 0
? q 0 ) public double earnings()
return quantity wagePerPiece
public String toString() return "Piece
worker " super.toString()
50
// Fig. 9.9 HourlyWorker.java // Definition of
class HourlyWorker public final class
HourlyWorker extends Employee private double
wage // wage per hour private double hours
// hours worked for week public
HourlyWorker( String first, String last, double
w, double h ) super( first, last ) //
call superclass constructor setWage( w )
setHours( h ) public void
setWage( double w ) wage ( w gt 0 ? w
0 ) public void setHours( double h )
hours ( h gt 0 h lt 168 ? h 0 )
public double earnings() return wage
hours public String toString()
return "Hourly worker " super.toString()
51
// Fig. 9.9 Test.java // Driver for Employee
hierarchy import javax.swing.JOptionPane import
java.text.DecimalFormat public class Test
public static void main( String args )
Employee ref // superclass reference
String output "" Boss b new Boss(
"John", "Smith", 800.00 ) CommissionWorker
c new CommissionWorker( "Sue", "Jones",
400.0, 3.0, 150)
PieceWorker p new PieceWorker( "Bob", "Lewis",
2.5, 200 ) HourlyWorker h new
HourlyWorker( "Karen", "Price", 13.75, 40 )
DecimalFormat precision2 new DecimalFormat(
"0.00" )
52
ref b // Employee reference to a Boss
output ref.toString() " earned "
precision2.format( ref.earnings() ) "\n"
b.toString() " earned " precision2.format(
b.earnings() ) "\n" ref c //
Employee reference to a CommissionWorker
output ref.toString() " earned "
precision2.format( ref.earnings() ) "\n"
c.toString() " earned " precision2.format(
c.earnings() ) "\n" ref p //
Employee reference to a PieceWorker output
ref.toString() " earned "
precision2.format( ref.earnings() ) "\n"
p.toString() " earned " precision2.format(
p.earnings() ) "\n" ref h //
Employee reference to an HourlyWorker
output ref.toString() " earned "
precision2.format( ref.earnings() ) "\n"
h.toString() " earned " precision2.format(
h.earnings() ) "\n" JOptionPane.showMess
ageDialog( null, output, "Demonstrating
Polymorphism", JOptionPane.INFORMATION_MESSAGE
) System.exit( 0 )
53
(No Transcript)
54
OO Programming
  • Dynamic binding (late binding)
  • accommodates new classes
  • object's type does not need to be known at
    compile time
  • at execution time, method call matched with
    object

55
OO Programming
  • Interface
  • keyword interface
  • has set of public abstract methods
  • can contain public final static data

56
OO Programming
  • Using Interfaces
  • class specifies it uses interface with keyword
    implements
  • multiple interfaces use comma-separated list
  • class must define all abstract methods in
    interface
  • must use same number of arguments, same return
    type
  • using interface like signing a contract
  • "I will define all methods specified in the
    interface"
  • same "is a" relationship as inheritance

57
OO Programming
  • Using Interfaces
  • Interfaces used in place of abstract classes
  • used when no default implementation
  • typically public data types
  • interface defined in its own .java file
  • interface name same as file name
  • previous interfaces
  • we have used interface ActionListener
  • required to define actionPerformed

58
OO Programming
  • Another use of Interfaces
  • define a set of constants used by many classes
  • public interface Constants
  • public static final int ONE 1
  • public static final int TWO 2
  • public static final int THREE 3

59
// Definition of interface Square public
interface Square public int area(int i)
public int perimeter(int i) // Definition of
interface Shape public class intSquare implements
Square public int area(int i) return
ii public int perimeter(int i)
return 4i
60
// Fig. 9.11 Shape.java // Definition of
interface Shape public class Shape public
abstract double area() public abstract double
volume() public abstract String getName()

61
OO Programming
  • Inner classes
  • till now, all classes defined at file scope (not
    inside other classes)
  • inner classes defined inside other classes
  • can access all members of outer class
  • no special handles needed
  • anonymous inner class (has no name)
  • frequently used with event handling

62
OO Programming
  • Notes on Inner Classes
  • every class (including inner classes) have their
    own .class file
  • named inner classes can be public, protected,
    private, or have package access (same
    restrictions as other members of a class)
  • to access outer class's this reference
  • OuterClassName.this

63
OO Programming
  • Notes on Inner Classes
  • inner class can be static
  • does not require object of outer class to be
    defined
  • does not have access to outer class's non-static
    members
  • To create an object of another class's inner
    class
  • Create an object of outer class and assign it a
    reference (ref)
  • type statement of form
  • OuterClassName.InnerClassName innerRef ref.new
    InnerClassName()
Write a Comment
User Comments (0)
About PowerShow.com