Polymorphism Contents Forms of polymorphism

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Inheritance Contents 1.Fundamentals 2.Generalization 3.Constructors and Derived Classes 4.Visibility Modifiers 5.Abstract Classes 6.Interfaces.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Structured Programming Good for programming in the small Often doesn't scale up Limitations –Changes at top may affect lower-level algorithms –Code reuse.
Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.
Programming in Java CSCI-2220 Object Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Object Oriented Programming
Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
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
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
1 More About Derived Classes and Inheritance Chapter 9.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Object-Oriented Programming Concepts
Inheritance ITI1121 Nour El Kadri.
Chapter 11 Inheritance and Polymorphism
Ch 10- Advanced Object-Oriented Programming Features
Inheritance and Polymorphism
Chapter 11: Inheritance and Polymorphism
Polymorphism.
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
Object Oriented Programming in Java
Week 4 Object-Oriented Programming (1): Inheritance
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Object Oriented Programming
CS 302 Week 11 Jim Williams, PhD.
Polymorphism 11-Nov-18.
Lecture 23 Polymorphism Richard Gesick.
Chapter 9 Inheritance and Polymorphism
Polymorphism 2nd Lecture
Chapter 9: Polymorphism and Inheritance
Week 6 Object-Oriented Programming (2): Polymorphism
CS18000: Problem Solving and Object-Oriented Programming
Java Inheritance.
Object Oriented Programming
CIS 199 Final Review.
Chapter 11 Inheritance and Polymorphism
CS 200 More Classes Jim Williams, PhD.
Chapter 11 Inheritance and Polymorphism Part 1
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Java String Class String is a class
Lecture 8 Object Oriented Programming (OOP)
Programming in C# CHAPTER 5 & 6
Computer Science II for Majors
Presentation transcript:

Polymorphism Contents Forms of polymorphism Polymorphic variables – late (run-time binding) Abstract classes – example, Shape Inheritance and polymorphism

parametric overloading 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 Shape is an abstract class with no implementation of area() and perimeter() area() perimeter() Rectangle Circle 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 be NO instances of an abstract class (no Shape objects) Concrete realizations of Shape Abstract Shape class public abstract class Shape { protected String shapeName; public Shape(String name) {shapeName = name;} public abstract double area ( ); public abstract double perimeter ( ); public String toString( ) {return shapeName;}; } Class MUST be qualified as abstract if one or more methods are abstract public class Circle extends Shape { private double radius; public Circle (double rad) { super (“Circle”); radius = rad; } public double area( ) { return Math.PI * radius * radius; } public double perimeter( ) { return 2.0 * Math.PI * radius; } public class Rectangle extends Shape{ protected double length, width; public Rectangle(double len, double wid) { super(“Rectangle”); length = len; width = wid; } public double area ( ) {return length * width;} public double perimeter ( ) { return 2.0 * (length + width); }

The Object-oriented Programming Paradigm Square extends Rectangle Additional inheritance public class Square extends Rectangle { public Square (double side) { super (“Square”); length = width = side; } Shape Attributes inherited from Rectangle BUT! There is a problem! Circle Rectangle super(“Square”); refers to the base class of Square – which is Rectangle. We need to add a constructor: Rectangle(String name) { super(name); } to class Rectangle -- to “pass the string Square” up to the base class. Add a class Square to the collection of shapes. Square

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 ShapeShifter { public static void main (String [ ] args) { Shape [ ] shapeList = new Shape[5]; shapeList[0] = new Circle(3.0); shapeList[1] = new Rectangle(3.0, 4.0); shapeList[2] = new Rectangle(2.5, 7.5); shapeList[3] = new Circle(2.5); shapeList[4] = new Square(5.0); for (int i = 0; i < shapeList.length; i++) { System.out.print (shapeList[i].toString( ) + “ ” ); System.out.print (shapeList[i].area( ) + “ ”); System.out.println (shapeList[i].perimeter( )); } Create an array to hold objects of (derived from) class Shape Create objects of the derived classes and put them in shapeList 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; private String says; Attributes Constructor public Animal(String str, String s2){ name = new String(str); says = new String(s2); } Behavior public void speak( ) { System.out.println(name+says); }

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 ) { super(“Dog”, says); } public void move ( ) { System.out.println(“ -- I run”); public class Bird extends Animal { public Bird(String says) { super(“Bird”,says); } public void move ( ) { 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 String name; String says; public Animal(String, String) public void speak( ) Base class Derived classes extend the base class Dog Bird public Dog(String) public void move( ) public Bird(String)

The Object-oriented Programming Paradigm Inheritance Consider the following application (class AnimalHouse) public class AnimalHouse { private Dog Lassie; private Bird TweetyBird; private Animal Felix; public AnimalHouse ( ) { Lassie = new Dog(“ -- bow-wow”); TweetyBird = new Bird(“ -- tweet-tweet”); Felix = new Animal(“Cat”, “ – meoow”); } public void animalAct( ) { Lassie.speak( ); TweetyBird.speak( ); Felix.speak( ); Lassie.move( ); TweetyBird.move( ); public static void main(String [ ] args) { AnimalHouse zoo = new AnimalHouse( ); zoo.animalAct( ); } }//end class AnimalHouse Output The class contains three attributes (“data” members) that are objects of the base class Animal, or one of the classes derived from it. The constructor allocates memory for the three private objects and initializes their attributes. The application class (AnimalHouse) contains a main function that creates an instance of the class and tells the AnimalHouse object zoo to execute its animalAct( ) operation. Dog -- bow-wow Bird -- tweet-tweet Cat -- meoow -- 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 baseVal) {…} public void increment( ) {…} public void reset( ) {…} public int viewCount( ) {…} } We may use composition to build a Clock out of Counter objects

The Object-oriented Programming Paradigm Composition public class Clock { private Counter hours, mins, secs; public Clock( ) hours = new Counter(24); mins = new Counter(60); secs = new Counter(60); } public void tick( ) { secs.increment( ); if (secs.viewCount( ) == 0) { mins.increment( ); if((secs.viewCount( )==0) && (mins.viewCount( ) == 0)) hours.increment( ); These Counter objects are not accessible outside of a Clock object. Each Clock object must hold its own set of Counter objects Clock methods are implemented by the Counter components In an assignment you will add methods set( ) and viewHr(), viewMin( ), and viewSec( ) to this class

The Object-oriented Programming Paradigm Inheritance Suppose we want to construct a new class called AlarmClock that has all of the features of a Clock, but adds an alarm as well. Inherits from class Clock public class AlarmClock extends Clock { private boolean alarmOn; private int hrSet, minSet; public AlarmClock( ) {alarmOn = false;} //the alarm is not set initially public void setAlarm(int hr, int min) { hrSet = hr; minSet = min; alarmOn = true; } public void tick( ) { super.tick( ); if ((viewHr( ) == hrSet)&&(viewMin() == minSet)&&alarmOn){ System.out.println(“ring, ring, ring”); public void resetAlarm( ) {alarmOn = false;} Additional attributes in an AlarmClock Additional methods in AlarmClock Override the implementation of tick( ) in parent Execute the version of this method in the parent class viewHr() and viewMin( ) are methods in an AlarmClock that are inherited from its parent

The Object-oriented Programming Paradigm Inheritance The constructor AlarmClock( ) initializes the boolean variable alarmOn to false, and leaves the initial alarm settings at the default values – hrSet = 0 and minSet = 0. The constructor for the base class does not take any parameters, and no additional initialization is needed to instantiate the 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 viewHr( ) and viewMin( ) are inherited from the base class and are available to any client of an AlarmClock object (including the methods of this class).

The Object-oriented Programming Paradigm Polymorphism and Genericity Genericity The only container object we have studied so far is the array. Arrays of any type can be declared, and the array operations such as Assignment ex. A[0] = assigned value of the declared type. Retrieval ex. Itemtype myVar = A[3]; //retrieve object at index 3 Length A.length 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 are 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 AlarmClock 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”); robin = new Bird( “ -- tweet-tweet”); Animal critter; critter = fido; critter.speak( ); critter = robin; } Make Animal reference to a derived class object Executes method speak( ) for a derived class object. Dog – ruff-ruff Bird – tweet-tweet

The Object-oriented Programming Paradigm critter.speak( ); Polymorphism critter = tweety; critter = fido; tweety = new Bird(“ tweet-tweet”); Animal critter; fido = new Dog(“ ruff-ruff”); critter.speak( ); tweet-tweet fido Dog ruff-ruff speak( ) move( ) tweety Bird tweet-tweet speak( ) move( ) critter critter ruff-ruff Animal base class features Not accessible by messages to critter

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 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. The basic unit of code is the class which is a template for creating run-time objects. A class encapsulates data (primitive types and object references) and the operations that can be performed on this data. 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. 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.) 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. 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. For container classes to be generally reusable, they must be generic – able to hold almost any kind of primitive type or object. Java provides automatic garbage collection, relieving the programmer of the need to ensure that unreferenced memory is regularly deallocated.