1 cosc2007 data structures ii chapter 9 class relationships

41
1 COSC2007 Data Structures II Chapter 9 Class Relationships

Upload: vernon-parrish

Post on 18-Jan-2016

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

1

COSC2007 Data Structures II

Chapter 9Class Relationships

Page 2: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

Topics

Inheritance & Polymorphism

Abstract Class

Class Relationship

Page 3: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 4: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 5: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 6: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 7: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 8: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 9: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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)

);

}

Page 10: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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;

Page 11: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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?

Page 12: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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.

Page 13: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 14: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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.

Page 15: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

The abstract Shape classpublic abstract class Shape { public abstract double area(); public abstract double circumference(); }

Shape

Circle Rect

Square

The Shape Hierarchy

Page 16: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 17: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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?

Page 18: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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?

Page 19: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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?

Page 20: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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?

Page 21: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 22: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

Casting

What would happen? Why?

Shape c = new Circle();double r = c.getRadius();

Shape

Circle Rect

Square

Page 23: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 24: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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;

Page 25: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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;

Page 26: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

26

Review ______ is the ability of a class to derive

properties from a previously defined class. Encapsulation Simulation Inheritance Polymorphism

Page 27: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

27

Review The class from which another class is

derived is known as the ______. base class subclass child class final class

Page 28: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

28

Review A subclass inherits all of the following

members of its superclass EXCEPT ______. public methods data fields constructors protected methods

Page 29: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

29

Review ______ enables the reuse of existing

classes. Encapsulation Inheritance Polymorphism Simulation

Page 30: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 31: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

31

Review The keyword ______ is used in the class

declaration of a subclass to indicate its superclass. inherits extends implements super

Page 32: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 33: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

33

Review The constructor of a subclass can call the

constructor of the superclass by using the ______ reference. extends new super import

Page 34: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 35: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

35

Review Dynamic binding is also known as ______.

early binding late binding package binding inheritance binding

Page 36: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 37: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

37

Review If the field modifier ______ is specified in a

method definition, the method cannot be overridden by a subclass. public protected final abstract

Page 38: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 39: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

39

Review Methods declared as ______ use static

binding. protected final public abstract

Page 40: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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

Page 41: 1 COSC2007 Data Structures II Chapter 9 Class Relationships

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