COP 3003 Object-Oriented Programming - Polymorphism Dr. Janusz Zalewski, Fall 2013 Prepared by Dr Dahai Guo.

Slides:



Advertisements
Similar presentations
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.
Advertisements

COP 3003 Object-Oriented Programming - Inheritance Dr. Janusz Zalewski, Fall 2013 Prepared by Dr Dahai Guo.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Advanced Programming in Java
Sadegh Aliakbary Sharif University of Technology Fall 2010.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Evan Korth New York University abstract classes and casting Professor Evan Korth New York University.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
CPSC150 Interfaces Chapter CPSC150 Inheritance Review No different than any other class. Has no access to or information about subclasses class.
Chapter 10 Classes Continued
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Abstract Classes and Interfaces
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
Object-Oriented Programming: Polymorphism
Advanced Inheritance Concepts. In this chapter, we will cover: Creating and using abstract classes Using dynamic method binding Creating arrays of subclass.
Object Oriented Programming using Java - Polymorphism
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
 2005 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Inheritance.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
TCP1201 OOPDS Lecture 4 1. Learning Objectives  To understand upcasting & downcasting  To understand static polymorphism and dynamic polymorphism 
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
O O P Polymorphism Object Oriented Programming Prepared & Presented by: dr.Ismail Farahat Chapter 4.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
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,
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Object Oriented programming Instructor: Dr. Essam H. Houssein.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CS 5JA Introduction to Java Pop Quiz Define/Explain encapsulation. In object-oriented programming, encapsulation refers to the grouping of data and the.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
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)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
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
Object-Oriented Programming: Polymorphism
Inheritance and Polymorphism
abstract classes and casting objects
Object-Oriented Programming: Polymorphism
More inheritance, Abstract Classes and Interfaces
Object-Oriented Programming: Polymorphism
Based on slides from Deitel & Associates, Inc.
Advanced Programming Behnam Hatami Fall 2017.
Java Inheritance.
Object-Oriented Programming: Polymorphism
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation transcript:

COP 3003 Object-Oriented Programming - Polymorphism Dr. Janusz Zalewski, Fall 2013 Prepared by Dr Dahai Guo

Outline Introduction to Polymorphism Superclass Reference and Subclass Object Abstract Classes and Methods instanceof operator Creating and Using Interfaces

Introduction to Polymorphism (1/7) Based on and enabled by inheritance. Enables us to “program in the general” rather than “program in the specific”. Makes systems easily extensible. –New classes can be added with little or no modification to the general portions of the program.

Introduction to Polymorphism (2/7) class Animal public void move() class Mammal public void move() class Fish public void move() class Tortoise public void move() class Cat public void move() class Dog public void move()

Introduction to Polymorphism (3/7) Problem: –In classes Animal and Mammal, the move( ) method is hard to define, because it is too general (or abstract). –Keep this in mind.

Introduction to Polymorphism (4/7) What can polymorphism do for us? –Example: you want to write a simulation program where 100 animals are created randomly and are moving. Without polymorphism –Generate four random numbers –Create four arrays (cats, dogs, fish, tortoises) using the random numbers as the sizes What if we want to be random when creating each object? In other words, the program runs the random number generation method 100 times, instead of only four.

Introduction to Polymorphism (5/7) What can polymorphism do for us? –Animal animals[ ]=new Animal[100]; animal[0] animal[1] animal[99] An Animal reference can refer to any class’s object as long as this class directly or indirectly inherits class Animal.

Introduction to Polymorphism (6/7) What can polymorphism do for us? –Animal animals[ ]=new Animal[100]; 1./* creating 100 Animal-derived objects */ 2.… 3.for(int i=0; i<100;i++){ 4. // we do not know which actual object 5. // animals[i] references to, 6. // but polymorphism can decide the sub- 7. // class and invoke correct method 8. animals[i].move(); 9.} Question: Do we still need to implement the move method for class Animal?

Introduction to Polymorphism (7/7) The two most important points of polymorphism: –A superclass reference refers to a subclass object. (Note the opposite is a syntax error.) –Which subclass’s method to invoke is decided at the execution time. In detail, it depends on the data type of the object.

Superclass Reference and Subclass Object (1/8) A program can create an array of superclass references that refer to objects of many subclass types. This is allowed because each subclass object is-a object of its superclass. This is referred to as dynamic binding.

Superclass Reference and Subclass Object (2/8) Anything wrong? –class Test1 { –} –class Test2 { –} –…… – Test1 test = new Test2(); –……

Superclass Reference and Subclass Object (3/8) Note in the “reference  object” relationship, the reference’s class must be the superclass of the object’s class or exactly the object’s class.

Superclass Reference and Subclass Object (4/8) 1.class CommissionEmployee { 2.} 3.class BasePlusCommissionEmployee 4. extends CommissionEmployee { 5.}

Superclass Reference and Subclass Object (5/8) 1.CommissionEmployee employee 2.= new BasePlusCommissionEmployee(…); 3.employee.toString(); // which method will be invoked? 4.employee.earnings(); // which method will bei nvoked 5.employee.getBaseSalary(); // which method will be invoked? Illegal Statement!

Superclass Reference and Subclass Object (6/8) Important: when invoking a subclass’s method through a superclass’s reference, this method must be declared in the super class. If the method is subclass-specific, the program must first cast the superclass reference to the subclass reference a technique known as downcasting.

Superclass Reference and Subclass Object (7/8) 1.employee.getBaseSalary(); // illegal statement 2.((BasePlusCommissionEmployee)employee).getBaseSalary();

Superclass Reference and Subclass Object (8/8) Benefit of polymorphism. –Animal animals[ ] = new Animal[100]; 1./* creating 100 Animal-derived objects */ 2.… 3.for(int i=0; i<100;i++){ 4. animals[i].move(); 5.} Question: If another Animal-based class is created, do we need to change anything to the for loop?

Abstract Classes and Methods (1/7) class Animal public void move() class Mammal public void move() class Fish public void move() class Tortoise public void move() class Cat public void move() class Dog public void move() Difficult to define, because only “animal” is too abstract.

Abstract Classes and Methods (2/7) Why do not we leave out the move method in class Animal? And what we actually want is to force the subclasses to implement this function. This can be achieved by abstract classes.

Abstract Classes and Methods (3/7) abstract class Animal public abstract void move() ; class Mammal public void move() class Fish public void move() class Tortoise public void move() class Cat public void move() class Dog public void move() Now, all the classes, except Animal, must implement method move to be instantiated.

Abstract Classes and Methods (4/7) Rules: –An abstract method is declared using keyword abstract. –Once a class has at least one abstract method, it must be declared as abstract class. –Important: abstract classes cannot be used to instantiate objects, because they are incomplete.

Abstract Classes and Methods (5/7) Rules: (cont) –If a superclass is an abstract class, its subclasses must implement all the abstract methods in order to be instantiated objects; otherwise they are also abstract. –The previous statement implies that both the superclass and subclass can be abstract.

Abstract Classes and Methods (6/7) abstract class Animal public abstract void move() ; abstract class Mammal Does not implement move() class Fish public void move() class Tortoise public void move() class Cat public void move() class Cat public void move() Class Mammal inherits abstract method move from class Animal and does not implement it. So method move remains abstract. Therefore, class Mammal is also abstract. Now both Animal and Mammal are abstract.

Abstract Classes and Methods (7/7) Rules: (cont) –Classes that can be used to instantiate objects are called concrete classes. –The subclass of an abstract superclass can be abstract or concrete, depending on whether it implements all the abstract method(s) in the superclass.

How Can We Find the Type of the Object? (1/7) SuperClass superRef; superRef=new SubClass1(); …… superRef=new SubClass2(); …… superRef=new SubClass3(); …… superRef can be used to point to different subclass objects.

How Can We Find the Type of the Object? (2/7) Sometimes, we want to figure out what type of object is referenced in order to call subclass-specific methods. –…… –// are you sure a SubClass1 object is referenced? –((SubClass1)superRef).method1(); –// are you sure a SubClass2 object is referenced? –((SubClass2)superRef).method2(); –// are you sure a SubClass3 object is referenced? –((SubClass3)superRef).method3();

How Can We Find the Type of the Object? (3/7) instanceof operator –Can help figure out what type of object is referenced 1.if (superRef instanceof SubClass1) { 2. // downcasting 3. ((SubClass1)superRef).method1(); 4.} 5.if (superRef instanceof SubClass2) { 6. // downcasting 7. ((SubClass2)superRef).method2(); 8.} 9.if (superRef instanceof SubClass3) { 10. // downcasting 11. ((SubClass3)superRef).method3(); 12.}

How Can We Find the Type of the Object? (4/7) Requirements of the operands of instanceof –The data type of the reference and the right operand must have inheritance relationship, directly or indirectly.

How Can We Find the Type of the Object? (5/7) Employee HourlyEmployeeCommissionEmployeeSalariedEmployee BasePlusCommissionEmployee

How Can We Find the Type of the Object? (6/7) instanceof operator –Anything wrong? 1.HourlyEmployee employee= 2. new HourlyEmployee(); 3.if(employee instanceof 4. BasePlusCommissionEmployee) { 5. System.out.println(“BasePlusCommissionEmployee”); 6.} HourlyEmployee and BasePlusCommissionEmployee has neither direct nor indirect inheritance relationship.

How Can We Find the Type of the Object? (7/7) Downcasting 1.Employee employee = 2. new BasePlusCommissionEmployee(); 3.…… 4.if(employee instanceof 5. BasePlusCommissionEmployee) { 6. employee.setLastName(“Johnson”); 7. ((BasePlusCommissionEmployee)employee). 8. setBaseSalary(1000); 9.}

Creating and Using Interfaces (1/12) Interfaces are abstract classes without non-abstract methods. An interface declaration begins with the keyword interface and contains only constants and abstract methods. All interface methods are implicitly public and abstract. All interface instance variables are implicitly public, static, and final.

Creating and Using Interfaces (2/12) Anything wrong? 1.interface MyInterface { 2.int i; 3.} i is final, so it must be initialized at the declaration.

Creating and Using Interfaces (3/12) Anything wrong? 1.interface MyInterface { 2.protected int test(); 3.} Any interface methods must be public and abstract.

Creating and Using Interfaces (4/12) To use an interface, a concrete class must specify that it implements the interface and must declare each method in the interface with the signature specified in the interface declaration. An interface reference can point to the objects of classes that implement it and their subclasses.

Creating and Using Interfaces (5/12) Anything wrong? 1.interface MyInterface { 2.int test(); 3.} 4.class MyClass implements MyInterface { 5. protected int test(); 6.} One cannot change the access control of the interface method.

Creating and Using Interfaces (6/12) Employee HourlyEmployeeCommissionEmployeeSalariedEmployee BasePlusCommissionEmployee Payable Invoice

Creating and Using Interfaces (7/12) 1.interface Payable { 2. double getPaymentAmount(); 3.} 4.class Invoice implements Payable { 5. public double getPaymentAmount() { 6. … 7. } 8. … 9.} 10.abstract class Employee implements Payable { 11. // getPaymentAmount() not implemented 12.}

Creating and Using Interfaces (8/12) Equivalent? 1.abstract class Payable { 2. public abstract double getPaymentAmount(); 3.} 4.class Invoice extends Payable { 5. public double getPaymentAmount() { 6. … 7. } 8. … 9.} 10.abstract class Employee extends Payable { 11. getPaymentAmount not implemented 12.}

Creating and Using Interfaces (9/12) Discussion: –One can often see, esp. in GUI programs, that classes are defined like class MyClass extends ExistingClass implements Interface1, Interface2, …Interfacex { // a class can implement multiple interfaces // implementations of interface methods }

Creating and Using Interfaces (10/12) Discussion (cont): –One often faces the following situation: There is some existing code. But the existing code cannot exactly solve a new problem. We want to take advantage of already-developed programs in solving the new problem.

Creating and Using Interfaces (11/12) Discussion (cont): Existing Program New Problem New Program extends implements

Creating and Using Interfaces (12/12) Discussion (cont): Existing Program New Problem New Program extends implements Super-Class Sub-Class Interface