Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the...

38
Polymorphism Polymorphism

Transcript of Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the...

Page 1: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

PolymorphismPolymorphism

Page 2: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

PolymorphismPolymorphism

• Several subclasses may have different methods for accomplishing the same/similar behavior– You don’t care about the details when you call

a method, provided you know that the object can perform a method with that signature

– E.g. you have a simulated ecology with animals in it (SimZoo) and want to make the animals make noise

• But animals make noise in different ways

Page 3: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

PolymorphismPolymorphismclass Animal { public void makeNoise ( ) { System.out.println (“I am an animal.”); } // of makeNoise} // of Animal

class Fish extends Animal { public void makeNoise( ) { System.out.println (“Glug glug gurgle gurgle”); } // of makeNoise} // of Fish

class Bird extends Animal { public void makeNoise( ) { System.out.println(“Tweet tweet flap flap”); } // of makeNoise} // of Bird

Page 4: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Polymorphism (cont’d)Polymorphism (cont’d)

class Dog extends Animal{ public void makeNoise ( ) { System.out.println(“Sniff sniff woof woof”); } // of makeNoise

public void bark ( ) { System.out.println(“Arf Arf”); } // of bark

} // of Dog

Page 5: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

PolymorphismPolymorphismclass Driver { public static void main (String[ ] argv) { Animal[ ] animalArray = new Animal[3]; int iIndex; animalArray[0] = new Bird( ); animalArray[1] = new Dog( ); animalArray[2] = new Fish( ); for (iIndex=0; iIndex < animalArray.length; iIndex++) { animalArray[iIndex].makeNoise( ); } // of for

} // of main} // of Driver

Output: Tweet tweet flap flap Sniff sniff woof woof Glug glug gurgle gurgle

All animals can makeNoise, so any member of the array can makeNoise

Page 6: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

PolymorphismPolymorphism• Polymorphism means “taking many forms” ... an object of a given class can adapt take the form of any of its subclasses.

• Polymorphism means that the correct makeNoise( ) method will always be called.

• A subclass can be substituted for its superclass, e.g., a bird for an animal. “A bird is a animal.” Yes.

• The reverse is not true: can’t substitute superclass for a subclass, e.g., CANNOT substitute an animal for a bird. “An animal is a bird?” No. Not necessarily.

• A single interface for multiple behaviors: Only one interface for the method call. Multiple behaviors based on the subclass.

Page 7: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

class Driver2 { public static void main(String[ ] argv) { Animal[ ] = animalArray[3]; Dog d; int iIndex; animalArray[0] = new Bird( ); animalArray[1] = new Dog( ); animalArray[2] = new Fish( ); for (1=0; 1 < animalArray.length; iIndex++) if (animalArray[iIndex] instanceof Dog) { d = (Dog) animalArray[iIndex]; d.bark( ); } // if } // main} // Driver2

PolymorphismPolymorphism

We cast before calling bark()

because only dogs can bark. So some array members cannot execute the method

Page 8: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Casting:• used here to give an object of a superclass the form of the appropriate subclass, e.g.,

if (animalArray[iIndex] instanceof Dog) { animalArray[iIndex].bark(); }

would produce an error because objects of class Animal have no method called bark. So, we first cast what instanceof tells us is a Dog as a Dog.

if (animalArray[iIndex] instanceof Dog) { d = (Dog) animalArray[iIndex] d.bark( ); }

PolymorphismPolymorphism

Page 9: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Keyword instanceof: Used to interrogate an object to see if it is an instance of the specified class, e.g.

“Is this particular animal of class Dog?”

Casting … Why?Casting … Why?

Question: If Java can determine that a given Animal is or is nota Dog (via instanceof), then:

• Why the need to cast it to a Dog object before Java can recognize that it can bark?

• Why can’t Java do it for us?

Page 10: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Sourcecode

CompileBytecode

JVMInterpreter

Programruns

errors errors

Answer: difference between compile-time and run-time type checking.

Casting… Why?Casting… Why?

Compile-time Errors:

• Those that are discernable(seçmek,ayırt etmek) without the program executing.

• Question of language legality: “Is this a legal statement?” e.g.,

iIndex = strName;

Statement is not legal.

Run-time Errors:

• Those that are discernable only when the program is running with actual data values.

• Question of execution legality: “Is it legal for this variable to have the actual value assigned to it?”, e.g.,

animalArray[<badIndex>] = someAnimal

Statement is legal, but particular index value isn’t.

Page 11: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Casting… Why?Casting… Why?if (animalArray[iIndex] instanceof Dog){ animalArray[iIndex].bark();}

if (animalArray[iIndex] instanceof Dog) { d = (Dog) animalArray[iIndex]; d.bark( );}

• 1st line is legal.• 2nd line isn’t (unless array has Dog).• We can see that 1st line guarantees 2nd is legal.

• Compiler cannot see inter-statement dependencies… unless compiler runs whole program with all possible data sets!

• Runtime system could tell easily. . . BUT. . . We want most checking at compile-time for reasons of bothperformance and correctness.

• Here, legality of each line of code can be evaluated at compile time.• Legality of each line discernable without worrying about inter-statement dependencies, i.e., each line can stand by itself.• Can be sure that code is legal (not sometimes-legal).

A Good Use for Casting:

Resolving polymorphic ambiguities for the compiler.

Page 12: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

How Objects Are CreatedHow Objects Are CreatedDog d = new Dog();

An implicit super() calls parent class constructor first.

After all, a Dog is-a Animal, && is-a Object

d

Animal

Dog

Object

d

Animal

Dog

Object

d

Animal

Dog

Object

1.1.1.1. 2.2.2.2. 3.3.3.3.

Execution Time

Page 13: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Polymorphism...Polymorphism...Animal a = new Dog();

In some sense, casting is a type of polymorphic behavior.

a

Animal

Dog

Object

Animal a = new Dog(); Object o = a;

a

Animal

Dog

Objecto

We can create new references that point to different types in the same block of memory.

Page 14: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Dynamic BindingDynamic Binding

a

Animal

Dog

Objecto

System.out.println (o.toString());

.toString()

.toString()

.toString()

Dynamic binding provides runtime resolution to themost specific implementation possible.

When calling a method on a reference, the method must be present in the type (or inherited). However, the specific implementation called is determined at runtime. That’s ‘dynamic binding’.

Page 15: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Casting and PolymorphismCasting and Polymorphism

o.doYourThing(); // ERROR!

The calling type must have the method, either inits instance, or from its parent.

a

Animal

Dog

Objecto

.doYourThing()

.doYourThing()

No MethodNo Method Dynamic binding

does not work miracles. The reference type must have the method available (in the present class or inherited), or else a compilation error occurs.

Page 16: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Questions?Questions?

Page 17: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Abstract Methods & ClassesAbstract Methods & Classes

Page 18: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

An Abstract ClassAn Abstract Class

• A class like Animal is intended as a collector of common characteristics

• We want to refer to methods like makeNoise() polymorphically

• However, we have no idea how a generic animal really makes noise.

• In the example above, we used some meaningless surrogate code:

public void makeNoise ( ) {

System.out.println

(“I am an animal.”);

} // of makeNoise

Page 19: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

An Abstract ClassAn Abstract Class

• We could just give up and use an empty method like:public void makeNoise ( ) {

/* To be defined later */ }

• This, of course, does nothing, and we depend on child classes to implement these methods

• A software engineering tool that has been implemented in Java is the keyword abstract

• We can define the move method to be abstract:abstract public void makeNoise();

// Note: No body!!!

• Java will then require us to designate the class as being abstract

abstract public class animal...

Page 20: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

An Abstract ClassAn Abstract Class

• Subclasses of abstract classes must be either– abstract if they do not define all abstract methods with valid

method bodies– concrete

abstract class animal { abstract void makeNoise(); }

abstract class fourLegged {}

class Dog { void makeNoise() { // Code here! }}

class Man { void makeNoise() { // Code here! }}

Note: Cannot instantiate objects

of abstract classes!!!

Page 21: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

An Abstract ClassAn Abstract Class

• Using this technique Java can guarantee that all objects that come from classes that are in the animal class inheritance tree will have a makeNoise method

• This means that we can cast an object to be of type animal and invoke the makeNoise method and Java won't complain!

Object o;

o = getReferenceFromSomeContainerClass();

((animal)o).makeNoise();

Page 22: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Questions?Questions?

Page 23: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

InterfacesInterfaces

Page 24: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Multiple InheritanceMultiple Inheritance

Some languages allow multiple inheritance:

• Multiple inheritance leads to many potentially confusing naming problems (e.g. Pet.doYourThing() vs. Animal.doYourThing())• Growing consensus: the benefits of multiple inheritance aren’t worth the problems.• Java has single inheritance onlyonly.

• Java doesn’t allow multiple inheritance• Java does allow a construct that provides much of the functionality of multiple inheritance: The InterfaceThe Interface

Animal

Dog

Pet

Two parent classes,one child class

Page 25: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Interfaces DefinedInterfaces Defined• The ultimate abstract class - contains nothing but

constants and abstract method prototypes

• A class is said to implement an interface if it provides suitable real methods for all of the abstract (virtual) methods of the interface

• the class implementing that interface then behaves as if it were inheriting from a parent class, with one huge advantage:

– Since you implement all of the abstract methods yourself, there is no other hidden, inherited stuff to collide with

• You can therefore implement as many interfaces as you wish with no fear of the problems of multiple inheritance

Page 26: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

ExampleExample

• We want a container class that can order or sort the items it contains.

• How can we compare two objects?• We make a kind of specification:• We promise that any object we want to store in this

sorting container class will have a method allowing it to be compared to other objects.

• How do we formalize this?• Use of an interface

Page 27: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

ComparableComparable

public abstract interface Comparable

{

abstract int compareTo(Object o);

}

Page 28: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Suppose...Suppose...

• We want to store Box objects and for our purposes we decide to compare boxes based on their volume.

• We modify our Box class thusly:

Page 29: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Suppose...Suppose...public class Box implements Comparable {

... // Same as before including getVolume methodpublic int compareTo(Object o) {

int retval = -1;if(o instanceOf Box) {

retVal = getVolume() - ((Box)o).getVolume();if(retVal == 0)

retVal = 0;else if(retVal > 0)

retVal = 1;else

retval = -1;}

return retval;}

}

Page 30: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Running the code...Running the code...

Called like this:

Box a = new Box(10, 20, 30);

Box b = new Box(2, 4, 6);

Box c = new Box(20, 10, 30);

System.out.println(a.compareTo(b)); ===> 1

System.out.println(a.compareTo(c)); ===> 0

System.out.println(b.compareTo(c)); ===> -1

System.out.println(a.compareTo("Hello")); ===> -1;

Page 31: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Don't be nervous!Don't be nervous!

• If we specify that something must be Comparable it's like saying:

• It must be an object (and it must implement the compareTo method).

• It’s just like making a contractual obligation to provide that method.

Page 32: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Another use!!!Another use!!!

Slick (kurnaz) way to provide constants

Page 33: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

We can create a class just for We can create a class just for constantsconstants

class Constants

{

public final static int FEETPERMILE = 5280;

public final static String PROMPT = "Enter a number";

public final static double PI = 3.141592;

}

• We use like this:

feet = miles * Constants.FEETPERMILE;

Page 34: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

If instead we sayIf instead we say

Interface Constants

{

public final static int FEETPERMILE = 5280;

public final static String PROMPT = "Enter a number";

public final static double PI = 3.141592;

}

• We use like this:class Box implements Constants {

...

feet = miles * FEETPERMILE;

Page 35: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Questions?Questions?

Page 36: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Visibility and AccessVisibility and Access

Visibility Modifier:

Access by: public protected private

Every class Yes No No

A subclass Yes Yes No

An instance of the class Yes Yes Yes

Always specify a visibility modifier.Guidelines:Only make public methods that are in the class’s “contract”Make all fields privateMake all other “private” methods protectedDon’t leave off the modifier unless you know about packages

Can a given object access a field or call a method?

Page 37: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Visibility and AccessVisibility and Access

Can a given object access a field or call a method?

Private Protected Public None

In the same classs Yes Yes Yes Yes

Subclass in the same package No Yes Yes Yes

Not a Subclass in the same package

No Yes Yes Yes

Subclass in a different package No Yes Yes No

Not a Subclass in a different package

No No Yes No

Page 38: Polymorphism. Polymorphism Several subclasses may have different methods for accomplishing the same/similar behavior –You don’t care about the details.

Questions?Questions?