Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.

Slides:



Advertisements
Similar presentations
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 4 : Polymorphism King Fahd University of Petroleum & Minerals College of Computer.
Advertisements

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.
Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 71 Inheritance Chapter 7. 2 Reminders Project 4 was due last night Project 5 released: due Oct 10:30 pm Project 2 regrades due by midnight.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
Chapter 10: Inheritance and Polymorphism
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Object-Oriented Programming: Polymorphism
Inheritance One of the biggest advantages of object-oriented design is that of inheritance. A class may be derived from another class, the base class.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Lecture 9 Polymorphism Richard Gesick.
CSE 501N Fall ‘09 15: Polymorphism October 22, 2009 Nick Leidenfrost.
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.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Programming With Java ICS Chapter 8 Polymorphism.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Inheritance in the Java programming language J. W. Rider.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
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.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Polymorphism. 3 main programming mechanisms that constitute OOP: 1. Encapsulation 2. Inheritance 3. Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism.
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.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Object-Oriented Programming: Polymorphism Chapter 10.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Polymorphism in Methods
Polymorphism, Interfaces & Operator Overloading
Inheritance and Polymorphism
Chapter 11: Inheritance and Polymorphism
Chapter 11 – Interfaces and Polymorphism
Types of Programming Languages
Object-Oriented Programming: Polymorphism
ATS Application Programming: Java Programming
Lecture 23 Polymorphism Richard Gesick.
Inheritance Chapter 7 Chapter 7.
Object-Oriented Programming: Polymorphism
Advanced Java Topics Chapter 9
Polymorphism CT1513.
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism and Type Casting
Fundaments of Game Design
Presentation transcript:

Polymorphism

Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept of dynamic or late binding

Polymorphism Polymorphism comes from Greek meaning “many forms.” In Java, polymorphism refers to the dynamic binding mechanism that determines which method definition will be used when a method name has been overridden. Thus, polymorphism refers to dynamic binding.

Polymorphism (Cont’d) Can treat an object of a subclass as an object of its superclass  A reference variable of a superclass type can point to an object of its subclass Person name, nameRef; PartTimeEmployee employee, employeeRef; name = new Person("John", "Blair"); employee = new PartTimeEmployee("Susan", "Johnson", 12.50, 45); nameRef = employee; System.out.println("nameRef: " + nameRef); nameRef: Susan Johnson wages are: $562.5

Polymorphism (Cont’d) Late binding or dynamic binding (run-time binding):  Method to be executed is determined at execution time, not compile time Polymorphism: to assign multiple meanings to the same method name Implemented using late binding

Polymorphism (Cont’d) The reference variable name or nameRef can point to any object of the class Person or the class PartTimeEmployee These reference variables have many forms, that is, they are polymorphic reference variables They can refer to objects of their own class or to objects of the classes inherited from their class

Polymorphism (Cont’d) Can declare a method of a class final using the keyword final If a method of a class is declared final, it cannot be overridden with a new definition in a derived class public final void doSomeThing(){ //... }

Polymorphism (Cont’d) Can also declare a class final using the keyword final If a class is declared final, then no other class can be derived from this class Java does not use late binding for methods that are private, marked final, or static

Polymorphism (Cont’d) You cannot automatically make reference variable of subclass type point to object of its superclass Suppose that supRef is a reference variable of a superclass type and supRef points to an object of its subclass:  Can use a cast operator on supRef and make a reference variable of the subclass point to the object  If supRef does not point to a subclass object and you use a cast operator on supRef to make a reference variable of the subclass point to the object, then Java will throw a ClassCastException —indicating that the class cast is not allowed

Polymorphism (Cont’d) Operator instanceof : determines whether a reference variable that points to an object is of a particular class type This expression evaluates to true if p points to an object of the class BoxShape ; otherwise it evaluates to false p instanceof BoxShape

Polymorphism (Cont’d) Interface variable holds reference to object of a class that implements the interface Measurable x ; Note that the object to which x refers doesn't have type Measurable ; the type of the object is some class that implements the Measurable interface Continued… x = new BankAccount(10000); x = new Coin(0.1, "dime");

Polymorphism (Cont’d) You can call any of the interface methods: Which method is called? double m = x.getMeasure();

Polymorphism (Cont’d) Depends on the actual object. If x refers to a bank account, calls BankAccount.getMeasure() If x refers to a coin, calls Coin.getMeasure() Polymorphism (many shapes): Behavior can vary depending on the actual type of an object Continued…

Polymorphism (Cont’d) Called late binding: resolved at runtime Different from overloading; overloading is resolved by the compiler (early binding)

Dynamic Binding Different objects can invoke different method definitions using the same method name. The type of object being referenced at the time of the method call, not the type of reference that was declared, determines which method is invoked. For example, if the reference b references a Box object and the reference t references a Triangle object, b and t invoke different definitions of the method drawAt() even of b and t are declared to be of type Figure.

Dynamic Binding (Cont’d) Consider the following example: Figure f; Box b = new Box(1, 4, 4); f = b; f.drawAt(2); Triangle t = new Triangle(1,2); f = t; f.drawAt(2);

The method drawAt() is inherited from class Figure and is not overridden. But, method drawHere() is invoked within the definition of method drawAt(), and method drawHere() is overridden. The type of object referred to by f determines which method drawHere() is invoked. Dynamic Binding (Cont’d)

Type Checking and Dynamic Binding Recall that an object reference to an ancestor class can refer to an object of a descendant class. However, you can invoke only a method in class Person with the variable p. Employee e = new Employee(); Person p; p = e;

However, if a method is overridden in the class Employee, and variable p references an Employee object, then the method in class Employee is used. The variable determines what methods can be used, but the type referenced by the object determines which definition of the method will be used. Type Checking and Dynamic Binding (Cont’d)

To use a method name in the class Employee with an object named by the variable p of type Person, use a type cast. Example: Employee e = (Employee)p; e.setEmployeeNumber(5678);

However, even a type cast cannot fool Java! Example: will use the definition of the method drawHere() given in class Box, not the definition of drawHere() given in class Figure. Type Checking and Dynamic Binding (Cont’d) Box b = new Box (1, 4, 4); Figure f = (Figure)b; f. drawHere()

You are unlikely to assign an object of a descendant type to a variable of a parent type, at least not directly. But, such an assignment can occur indirectly by providing an argument of a descendant type for a method that has a parameter of an ancestor type. Type Checking and Dynamic Binding (Cont’d)

Dynamic Binding with the toString() Method Recall the method toString() typically is used to prepare and return a string, describing an object, for output to the screen. The name of this method can be omitted, thanks to dynamic binding, because one definition of method println() expects a single argument of type Object which it uses to invoke the method toString() associated with the object.

Subtle Difference Dynamic binding refers to the process carried out by the computer. Polymorphism can be thought of as something objects do. Polymorphism, encapsulation, and inheritance, and considered to be the main features of object-oriented programming.

A Better equals() Method Sometimes the method equals() from class Object is overloaded when it should have been overridden.  This occurs when its parameter is not of type Object. Usually, this is all right.

A Better equals() Method (Cont’d) But, if the method equals() is called with an object of class Object as its argument, the method equals() from class Object will be invoked. The problem is fixed by changing the formal parameter in the overriding method so that it is a parameter of type Object.

However, this allows the argument to be any type of object, which can produce a run-time error. But, we can determine if an object is of the correct type using: Finally, we should return false when comparing an object to a null reference. A Better equals() Method (Cont’d) Object instanceof Class_Name

The improved equals() method: A Better equals() Method (Cont’d) public boolean equals(Object otherObject) { if(otherObject == null) return false; else if(!(otherObject instanceof Student)) return false; else { Student otherStudent = (Student) otherObject; // Downcast!! return (this.studentNumbemer == otherStudent.studentNumber)); }

Benefits of Polymorphism Polymorphism enables programmers to deal in generalities and let the execution-time environment handle the specifics. Programmers can command objects to behave in manners appropriate to those objects, without knowing the types of the objects (as long as the objects belong to the same inheritance hierarchy).

Polymorphism promotes extensibility: Software that invokes polymorphic behavior is independent of the object types to which messages are sent. New object types that can respond to existing method calls can be incorporated into a system without requiring modification of the base system. Only client code that instantiates new objects must be modified to accommodate new types. Benefits of Polymorphism (Cont ’ d)

Typical reference assignments Testing Polymorphism

Assign a reference to a basePlusCommissionEmployee object to a CommissionEmployee3 variable Polymorphically call basePlusCommissionEmployee ’s toString method Testing Polymorphism (Cont ’ d)