Polymorphism Contents 1 Forms of polymorphism 2 Polymorphic






















- Slides: 22
Polymorphism Contents 1. Forms of polymorphism 2. Polymorphic variables – late (run-time binding) 3. Abstract classes – example, Shape 4. Inheritance and polymorphism
Polymorphism Forms of poymorphism operator overloading Exmple – the + operator has different implementations with different arguments parametric overloading Example – overloading sqr in java. Math polymorphic variables
The Object-oriented Programming Paradigm Polymorphic Variables Shape is an abstract class with no implementation of area() and perimeter() Circle area() perimeter() Rectangle area() perimeter() Circle and Rectangle are concrete classes with their own separate implementations of the methods area() and Perimeter()
The Object-oriented Programming Paradigm Abstract Classes There can berealizations NO instances of an Concrete of Shape Abstract Shape class abstract class (no Shape objects) public abstract class Shape { protected String shape. Name; Class MUST be qualified as public Shape(String name) {shape. Name = name; } abstract if one or more public abstract double area ( ); methods are abstract public abstract double perimeter ( ); public String to. String( ) {return shape. Name; }; } public class Circle extends Shape { private double radius; public class Rectangle extends Shape{ public Circle (double rad) { protected double length, width; super (“Circle”); public Rectangle(double len, double wid) { radius = rad; super(“Rectangle”); } length = len; width = wid; public double area( ) { } return Math. PI * radius; } public double area ( ) {return length * width; } public double perimeter( ) { public double perimeter ( ) { return 2. 0 * Math. PI * radius; } return 2. 0 * (length + width); } } }
The Object-oriented Programming Paradigm Square extends Rectangle Additional inheritance public class Square extends Rectangle { Shape public Square (double side) { super (“Square”); length = width = side; Attributes inherited from Rectangle } } Circle Rectangle BUT! There is a problem! super(“Square”); refers to the base class of Square – which is Rectangle. We need to add a constructor: Add a class Square to the collection of shapes. Square Rectangle(String name) { super(name); } to class Rectangle -- to “pass the string Square” up to the base class.
The Object-oriented Programming Paradigm A vector of Shapes A container of Shape objects will execute their own area and perimeter methods
The Object-oriented Programming Paradigm Example (an array of Shapes) public class Shape. Shifter { public static void main (String [ ] args) { Shape [ ] shape. List = new Shape[5]; shape. List[0] = new Circle(3. 0); shape. List[1] = new Rectangle(3. 0, 4. 0); shape. List[2] = new Rectangle(2. 5, 7. 5); shape. List[3] = new Circle(2. 5); Create an array to hold objects of (derived from) class Shape Create objects of the derived classes and put them in shape. List[4] = new Square(5. 0); for (int i = 0; i < shape. List. length; i++) { System. out. print (shape. List[i]. to. String( ) + “ ” ); System. out. print (shape. List[i]. area( ) + “ ”); System. out. println (shape. List[i]. perimeter( )); } } } Iterate through the list and show area and perimeter of shapes Each derived class object executes its own area and perimeter methods
The Object-oriented Programming Paradigm Inheritance Consider a class Animal: Animal private String name; Attributes private String says; public Animal(String str, String s 2){ Constructor name = new String(str); says = new String(s 2); } public void speak( ) { System. out. println(name+says); } Behavior
The Object-oriented Programming Paradigm Inheritance Animal serves as the base class for several derived classes public class Dog extends Animal { public Dog(String says ) { public class Bird extends Animal { public Bird(String says) { super(“Dog”, says); super(“Bird”, says); } } public void move ( ) { System. out. println(“ -- I run”); } } System. out. println(“ -- I fly”); } Initialize base class attributes New methods can extend the behavior of the base class
The Object-oriented Programming Paradigm Inheritance Animal Base class String name; String says; public Animal(String, String) public void speak( ) Derived classes extend the base class Dog Bird public Dog(String) public Bird(String) public void move( )
The Object-oriented Programming Paradigm Inheritance Consider the following application (class Animal. House) public class Animal. House { private Dog Lassie; private Bird Tweety. Bird; private Animal Felix; public Animal. House ( ) { public static void main(String [ ] args) { Animal. House zoo = new Animal. House( ); zoo. animal. Act( ); } }//end class Animal. House Lassie = new Dog(“ -- bow-wow”); Tweety. Bird = new Bird(“ -- tweet-tweet”); Felix = new Animal(“Cat”, “ – meoow”); } public void animal. Act( ) { Lassie. speak( ); Tweety. Bird. speak( ); Felix. speak( ); Lassie. move( ); Tweety. Bird. move( ); The class contains Output three Theapplication constructor allocates The class attributes (“data” members) memory for the three private (Animal. House) contains a main that are objects of the base Dog -- bow-wow objects and initializes function that creates antheir class Animal, or one of the attributes. instance of the class and tells Bird --derived tweet-tweet classes from it. the Animal. House object zoo to Cat -- its meoow execute animal. Act( ) operation. -- I run -- I fly } Felix cannot receive a message move( )
The Object-oriented Programming Paradigm Composition Consider the class Counter described below public class Counter { private int count, base; public Counter(int base. Val) {…} public void increment( ) {…} public void reset( ) {…} public int view. Count( ) {…} } We may use composition to build a Clock out of Counter objects
The Object-oriented Programming Paradigm Composition public class Clock { These Counter objects are not private Counter hours, mins, secs; accessible outside of a Clock object. public Clock( ) hours = new Counter(24); Each Clock object must hold mins = new Counter(60); its own set of Counter objects secs = new Counter(60); } public void tick( ) { Clock methods are secs. increment( ); implemented by the Counter if (secs. view. Count( ) == 0) { components mins. increment( ); if((secs. view. Count( )==0) && (mins. view. Count( ) == 0)) hours. increment( ); } In an assignment you will add methods set( ) and } view. Hr(), view. Min( ), and view. Sec( ) to this class }
The Object-oriented Programming Paradigm Inheritance Suppose we want to construct a new class called Alarm. Clock that has all of the features of a Clock, but adds an alarm as well. public class Alarm. Clock extends Clock { private boolean alarm. On; Inherits from class Clock Additional attributes in an Alarm. Clock private int hr. Set, min. Set; public Alarm. Clock( ) {alarm. On = false; } //the alarm is not set initially public void set. Alarm(int hr, int min) { Additional methods in Alarm. Clock hr. Set = hr; min. Set = min; alarm. On = true; } public void tick( ) { Override the implementation of tick( ) in parent Execute the version of this method in the parent class super. tick( ); if ((view. Hr( ) == hr. Set)&&(view. Min() == min. Set)&&alarm. On){ System. out. println(“ring, ring”); } public void reset. Alarm( ) {alarm. On = false; } } view. Hr() and view. Min( ) are methods in an Alarm. Clock that are inherited from its parent
The Object-oriented Programming Paradigm Inheritance The constructor Alarm. Clock( ) initializes the boolean variable alarm. On to false, and leaves the initial alarm settings at the default values – hr. Set = 0 and min. Set = 0. The constructor for the base class does not take any parameters, and no additional initialization is needed to instantiate three Counter objects. The method tick( ) is overriden in the derived class. After every tick of the clock, a test is done to see whether it is time for the alarm to go off. The methods view. Hr( ) and view. Min( ) are inherited from the base class and are available to any client of an Alarm. Clock object (including the methods of this class).
The Object-oriented Programming Paradigm Polymorphism and Genericity The only container object we have studied so far is the array. any type can be declared, and the array operations such as Arrays of • Assignment ex. A[0] = • Retrieval ex. Itemtype my. Var = A[3]; //retrieve object at index 3 • Length A. length assigned value of the declared type. are syntactically independent of the type being stored in the array. We will have a need to construct (or use) various other container classes; and objects of container classes should be capable of holding any kind of object and provide the same functionality to the user regardless of their contents.
The Object-oriented Programming Paradigm Polymorphism There a variety of forms that polymorphism may take: 1. Overloading of function names. functions with different parameter lists may have the same identifier Ex: public static int sqr(int x) {…} public static double sqr(double x) {. . } The compiler determines which function to use by the type of the argument in the function call. An operation in a base class may be overridden in a derived class. Ex: function tick( ) is redefined in Alarm. Clock 2. Overloading of operators The operator + can be used to add pairs of any of the primitive types and to concatenate Strings. However, Java does not permit the programmer to define additional operations for any operator.
The Object-oriented Programming Paradigm Polymorphism 3. Polymorphic variables Run-time binding of a method call to a recipient object. Consider the following application public class Example { private Dog fido; private Bird robin; public static void main(String [ ] args) { fido = new Dog( “ -- ruff-ruff”); } } Make Animal reference to a derived class object robin = new Bird( “ -- tweet-tweet”); Animal critter; critter = fido; Dog – ruff-ruff critter. speak( ); critter = robin; critter. speak( ); Bird – tweet-tweet Executes method speak( ) for a derived class object.
The Object-oriented Programming Paradigm Polymorphism critter. speak( ); Bird(“ critter tweety Animal fido ===tweety; = new fido; critter; new Dog(“ ruff-ruff”); tweet-tweet”); critter. speak( ); tweet-tweet fido critter Dog Bird ruff-ruff speak( ) move( ) tweety tweet-tweet Animal base class features Not accessible by messages to critter speak( ) move( )
The Object-oriented Programming Paradigm Polymorphism In the previous example, an Animal object reference (critter) could attach to objects of the derived classes Dog and Bird and send messages to any of the methods that were common with (have the same interface – identifier, parameters, and return type) methods in the base class. Note! Casting could be used to be able to send messages to any of the derived class methods. (Bird)critter. move( ); //to obtain -- I fly
The Object-oriented Programming Paradigm Review 1. The object-oriented paradigm is a programming methodology that promotes the efficient design and development of software systems using reusable components that can be quickly and safely assembled into larger systems. 2. The basic unit of code is the class which is a template for creating runtime objects. 3. A class encapsulates data (primitive types and object references) and the operations that can be performed on this data. 4. The modifiers public, private, and protected (accessible to derived classes, but not to any other) limit and control the access that client code has to the attributes (data) of a class. Provides for security. 5. Classes can be composed from other classes. For example, Clocks can be constructed as an aggregate of Counters.
The Object-oriented Programming Paradigm Review (cont. ) 6. Inheritance provides a means of easily implementing the “is a” association between classes of objects. A dog “is a(n)” Animal with additional attributes and behaviors unique to dogs. 7. Much of the power of inheritance derives from the late (run-time) binding feature of an object-oriented language. We may have a container of Shapes where the individual Shape objects are instances of derived classes such as Circle, Square, Rectangle, and Triangle. A reference to a Shape, will be to one of these derived objects, and a message for the Shape object to calculate its area will be received by the area( ) method of the particular derived class object. 8. For container classes to be generally reusable, they must be generic – able to hold almost any kind of primitive type or object. 9. Java provides automatic garbage collection, relieving the programmer of the need to ensure that unreferenced memory is regularly deallocated.