Polymorphism.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
ABSTRACT CLASSES AND INTERFACES. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method without.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance and Polymorphism CS180 Fall Definitions Inheritance – object oriented way to form new classes from pre-existing ones –Superclass The.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Static and Dynamic Behavior Fall 2005 OOPD John Anthony.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
COP 3003 Object-Oriented Programming - Polymorphism Dr. Janusz Zalewski, Fall 2013 Prepared by Dr Dahai Guo.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Polymorphism & Interfaces
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
CS2 Module 26 Category: OO Concepts Topic: Interfaces Objectives –Interfaces.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
BY:- TOPS Technologies
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Agenda Warmup AP Exam Review: Litvin A2
Chapter 9 Inheritance and Polymorphism
Chapter 14 Abstract Classes and Interfaces
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

Polymorphism

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

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

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

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

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.

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

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

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?

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.

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.

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

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.

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.

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.

Questions?

Abstract Methods & Classes

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

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

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! } }

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

Questions?

Interfaces

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

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

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

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

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:

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;

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;

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.

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

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 = 3.141592; } We use like this: feet = miles * Constants.FEETPERMILE;

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 = 3.141592; } We use like this: class Box implements Constants { ... feet = miles * FEETPERMILE;

Questions?

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

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

Questions?