1 cosc2007 data structures ii chapter 9 class relationships
TRANSCRIPT
1
COSC2007 Data Structures II
Chapter 9Class Relationships
Topics
Inheritance & Polymorphism
Abstract Class
Class Relationship
Object Oriented Programming
Main components of OOP Inheritance (Base/Parent Class – Sub/Child Class) Encapsulation Polymorphism
Inheritance and polymorphism are the subject of chapter 9
Object Oriented Programming
Main components of OOP Inheritance (Base/Parent Class – Sub/Child Class) Encapsulation Polymorphism
Inheritance and polymorphism are the subject of chapter 9
Inheritance Inheritance example
Example: Class Ball is derived from class Sphere Ball inherits Sphere's attributes and methods
BalltheName: Stringequals(): booleandisplayStatistics (): void
SpheretheRadius: doubleradius (): doublearea(): doubleequals(): booleandisplayStatistics (): void
Inheritance
Class Ball extends Sphere Note that the Ball class has two data fields:
1) theRadius //inherited from Sphere Since theRadius is private in Sphere, Ball can only
reference it through methods
2) theName //new to the Ball class
What methods does Ball have?
Ball
Sphere
Inheritance Class Ball extends Sphere
A closer look at Ball's constructors The default constructor in class Ball here automatically calls the
default superclass constructor, then sets theName
public Ball () {
setName (“unknown”);
}
How about non-default constructor?
Ball
Sphere
Inheritance
Method equals is overridden The method equals in class Sphere
public boolean equals(Object rhs) {
if (rhs instanceof Sphere) &&
(theRadius = = ((Sphere)rhs).theRadius))
return true;
else return false;
} // end equals
Inheritance
Method equals is overridden In the class Ball, three conditions must be met
public boolean equals(Object rhs) {
return ( (rhs instanceof Ball) &&
(radius() == ((Ball)rhs).radius()) &&
(theName.compareTo(((Ball)rhs).theName)==0)
);
}
Inheritance displayStatistics is also overridden
Sphere's displayStatisticspublic void displayStatistics() {
System.out.println("\nRadius = " + radius() +
"\nDiameter = " + diameter() +"\nCircumference = " + circumference() + "\nArea = " +
area() + "\nVolume = " + volume());
} // end Sphere's displayStatistics
In the class Ballpublic void displayStatistics() {
System.out.print("\nStatistics for a "+ name());
super.displayStatistics( );
} // end Ball's displayStatistics;
Inheritance
Overridden methods Which method will the compiler use for these
calls to displayStaticis()?
Sphere mySphere=new Sphere();
Ball myBall=new Ball ();
myBall.displayStaticis(); //what will print?
mySphere.displayStatics(); //what will print?
Inheritance How overriding works
When a method is called by an object, it is compared against the
object’s class’s own method signatures The signature is the method name plus the argument list
If a match is found, that method is invoked
If a match is not found, the signature is compared against the
superclass’s method signature.
This process is repeated until a match is found.
A match is guaranteed because otherwise the Java compiler would
give an error.
Inheritance Dynamic binding
Sometimes the compiler cannot decide which version of an
overridden method to use The decision is then delayed until run time; until the program is executed
Example:
Ball myBall = new Ball(1.25, “golfball”);
Sphere mySphere = myBall;
mySphere.displayStatistics( );
Which displayStatistics method is used? polymorphism
Abstract Classes Suppose we have classes for shapes:
Rectangle, Square, Triangle, etc. All these shape classes likely have methods for computing
area() and circumference(). Would be nice to have a generic Shape class to help organize
these classes - make it simpler to define an array of different shapes, for example.
Make shape an abstract class. All of Shapes subclasses must implement the area() method, or
be abstract. Each of these methods are implemented differently.
The abstract Shape classpublic abstract class Shape { public abstract double area(); public abstract double circumference(); }
Shape
Circle Rect
Square
The Shape Hierarchy
Can now write code such as...
Shape [] shapes = new Shape[3];shapes[0] = new Circle(2.0);shapes[1] = new Rectangle(10.,20.);shapes[2] = new Circle(5.6);
double totalArea=0.0;for (int I=0; I<shapes.length; I++) totalArea=totalArea + shapes[I].area();
Question
public abstract class IsAbstractClass{public void test () {
S.O.P (“ I am a method”);
}
Is this class an abstract class? What are the rules?
Keywords final and static If a method is defined as final, the compiler can determine
which form of a method to use at compile time
This is static binding; sometimes called early binding
Methods declared as static also use early binding, since only
one version of the method is available for all classes
Override a static method?
Relationship between Classes
is-a Implies inheritance In an is-a relationship the subclass is-a type of the
superclasss For example myBall is-a Sphere
Whatever is true of Ball is true of Sphere
You can use Sphere as a type for Ball because they are
type compatible Is the other way around true?
Relationship between Classesis-part-of or has-a If class A is-part-of class B then there is no
inheritance Some negotiation between A and B for
responsibilities may be needed Example: Assume A contains a list that B
uses Who sorts the list? A or B? Country /Province?
Relationship between Classes Object type compatibility and type casting
The system will automatically type cast a subclass into a
superclass since they are type compatible
It does this since it is guaranteed that whatever is true of the
superclass or interface is true of the subclass
The opposite is not true It is up to you to make sure that an object of type Comparable or
Object is type String before you explicitly type cast it
Casting
What would happen? Why?
Shape c = new Circle();double r = c.getRadius();
Shape
Circle Rect
Square
How do we use this Shape as a Circle?
Is this ok?
How about this one?
Shape c = new Circle();double r = ((Circle)c).getRadius();
forces c to act as a circle
Shape square = new Shape ();double r = ((Circle)square).getRadius();
Widening Conversions
This is a widening conversion. obj -- an Object variable -- now references something more specific, namely a String.
String s = new String(“hello”);Object obj;obj = s;
Narrowing Conversions and Casting
String s = new String(“bye”);String t;Object obj;
obj = s;t = obj; // NO NO NO !!!
// you must CAST
t = (String) obj;
26
Review ______ is the ability of a class to derive
properties from a previously defined class. Encapsulation Simulation Inheritance Polymorphism
27
Review The class from which another class is
derived is known as the ______. base class subclass child class final class
28
Review A subclass inherits all of the following
members of its superclass EXCEPT ______. public methods data fields constructors protected methods
29
Review ______ enables the reuse of existing
classes. Encapsulation Inheritance Polymorphism Simulation
30
Review A method in a subclass is said to ______
an inherited method if it has the same method declarations as the inherited method. copy override overload cancel
31
Review The keyword ______ is used in the class
declaration of a subclass to indicate its superclass. inherits extends implements super
32
Review A superclass method can be accessed by
a subclass, even though it has been overridden by the subclass, by using the ______ reference. super final Static new
33
Review The constructor of a subclass can call the
constructor of the superclass by using the ______ reference. extends new super import
34
Review Inheritance should only be used when a(n)
______ relationship exists between the superclass and the subclass. is-a has-a has-many similar-to
35
Review Dynamic binding is also known as ______.
early binding late binding package binding inheritance binding
36
Review ______ is the ability of a variable name to
represent, during program execution, instances of different but related classes that descend from a common superclass. Inheritance Containment Polymorphism Encapsulation
37
Review If the field modifier ______ is specified in a
method definition, the method cannot be overridden by a subclass. public protected final abstract
38
Review If a method definition in a superclass has
the field modifier ______, a subclass is required to override the method. static protected Final abstract
39
Review Methods declared as ______ use static
binding. protected final public abstract
40
Review A method that has the same name but a
different set of parameters as an existing method is said to ______ the original method. bind cancel Override overload
41
Review Which of the following is true about an
abstract class? it can be instantiated it can contain zero or more abstract methods it cannot be inherited by other classes it cannot contain data fields