Presentation is loading. Please wait.

Presentation is loading. Please wait.


Similar presentations

Presentation on theme: "Polymorphism."— Presentation transcript:

1 Polymorphism

2 Polymorphism 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

3 Polymorphism class Animal { public void makeNoise ( ) {
System.out.println (“I am an animal.”); } // of makeNoise } // of Animal class Fish extends Animal { public void makeNoise( ) { (“Glug glug gurgle gurgle”); } // of Fish class Bird extends Animal { public void makeNoise( ) { System.out.println(“Tweet tweet flap flap”); } // of Bird

4 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

5 Polymorphism class 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

6 Polymorphism 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.

7 Polymorphism 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 We cast before calling bark() because only dogs can bark. So some array members cannot execute the method

8 Polymorphism 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. d = (Dog) animalArray[iIndex] d.bark( );

9 Casting … Why? 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?” Question: If Java can determine that a given Animal is or is not a 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?

10 Casting… Why? Answer: difference between compile-time and run-time type checking. Source code Compile Byte code JVM Interpreter Program runs errors errors 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. 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.

11 Casting… Why? } if (animalArray[iIndex] 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 both performance 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.

12 How Objects Are Created
Dog d = new Dog(); 1. 2. 3. d Animal Dog Object d Animal Dog Object d Animal Dog Object Execution Time An implicit super() calls parent class constructor first. After all, a Dog is-a Animal, && is-a Object

13 Polymorphism... Animal a = new Dog();
We can create new references that point to different types in the same block of memory. a Animal Dog Object a Animal Dog Object o Animal a = new Dog(); Object o = a; In some sense, casting is a type of polymorphic behavior.

14 Dynamic Binding System.out.println (o.toString());
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’. a Animal Dog Object o .toString() .toString() .toString() System.out.println (o.toString()); Dynamic binding provides runtime resolution to the most specific implementation possible.

15 Casting and Polymorphism
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. a Animal Dog Object o .doYourThing() No Method o.doYourThing(); // ERROR! The calling type must have the method, either in its instance, or from its parent.

16 Questions?

17 Abstract Methods & Classes

18 An 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

19 An 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...

20 An Abstract Class Subclasses of abstract classes must be either
abstract if they do not define all abstract methods with valid method bodies concrete Note: Cannot instantiate objects of abstract classes!!! abstract class animal { abstract void makeNoise(); } abstract class fourLegged { } class Man { void makeNoise() { // Code here! } } class Dog { void makeNoise() { // Code here! } }

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

22 Questions?

23 Interfaces

24 Multiple Inheritance Some languages allow multiple inheritance: Animal
Pet Two parent classes, one child class Dog 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 only. Java doesn’t allow multiple inheritance Java does allow a construct that provides much of the functionality of multiple inheritance: The Interface

25 Interfaces 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

26 Example 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

27 Comparable public abstract interface Comparable {
abstract int compareTo(Object o); }

28 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:

29 Suppose... public class Box implements Comparable {
... // Same as before including getVolume method public 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;

30 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;

31 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.

32 Slick (kurnaz) way to provide constants
Another use!!! Slick (kurnaz) way to provide constants

33 We can create a class just for constants
class Constants { public final static int FEETPERMILE = 5280; public final static String PROMPT = "Enter a number"; public final static double PI = ; } We use like this: feet = miles * Constants.FEETPERMILE;

34 If instead we say We use like this: Interface Constants {
public final static int FEETPERMILE = 5280; public final static String PROMPT = "Enter a number"; public final static double PI = ; } We use like this: class Box implements Constants { ... feet = miles * FEETPERMILE;

35 Questions?

36 Visibility and Access Can a given object access a field or call a method? 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 private Make all other “private” methods protected Don’t leave off the modifier unless you know about packages

37 Visibility and Access Can a given object access a field or call a method? Private Protected Public None In the same classs Yes Subclass in the same package No Not a Subclass in the same package Subclass in a different package Not a Subclass in a different package

38 Questions?

Download ppt "Polymorphism."

Similar presentations

Ads by Google