Polymorphism 2nd Lecture

Slides:



Advertisements
Similar presentations
CMSC 202 Inheritance. Aug 6, Object Relationships An object can have another object as one of instance variables. The Person class had two Date.
Advertisements

Comp 249 Programming Methodology Chapter 7 - Inheritance – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
CS102--Object Oriented Programming Lecture 7: – Inheritance Copyright © 2008 Xiaoyan Li.
Chapter 8 Polymorphism and Abstract Classes Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
CS102--Object Oriented Programming Lecture 9: – Polymorphism Copyright © 2008 Xiaoyan Li.
Chapter 7 Inheritance Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
CS102--Object Oriented Programming Lecture 10: – Abstract Classes Copyright © 2008 Xiaoyan Li.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Comp 249 Programming Methodology Chapter 8 - Polymorphism Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal,
CMSC 202 Inheritance II. Version 10/102 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
What is inheritance? It is the ability to create a new class from an existing class.
CMSC 202 Inheritance I Class Reuse with Inheritance.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Modern Programming Tools And Techniques-I
Polymorphism and Abstract Classes
Lecture 12 Inheritance.
Inheritance and Polymorphism
COMP 2710 Software Construction Inheritance
Polymorphism 2nd Lecture
Polymorphism 2nd Lecture
Comp 249 Programming Methodology
Classes and Objects 2nd Lecture
Computer Science II Exam 1 Review.
Chapter 9 Inheritance and Polymorphism
Inheritance 2nd Lecture
Chapter 7 Inheritance Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 14 Inheritance Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Classes and Objects Encapsulation
Polymorphism 2nd Lecture
Comp 249 Programming Methodology
Inheritance I Class Reuse with Inheritance
CMSC 202 Interfaces.
Extending Classes.
Java Programming Language
Chapter 9: Polymorphism and Inheritance
CMSC 202 Polymorphism.
Inheritance 2nd Lecture
CMSC 202 Inheritance.
Inheritance.
Class Reuse with Inheritance
Java Classes and Objects 3rd Lecture
Inheritance Inheritance is a fundamental Object Oriented concept
Inheritance 2nd Lecture
Abstract methods and classes
مظفر بگ محمدی دانشگاه ایلام
مظفر بگ محمدی دانشگاه ایلام
CMSC 202 Interfaces.
CMSC 202 Generics.
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chapter 11 Inheritance and Polymorphism Part 1
CMSC 202 Inheritance II.
CMSC 202 Exceptions.
CMSC 202 Interfaces.
Classes and Objects Object Creation
Chapter 8 Abstract Classes.
Chapter 7 Inheritance.
CS 240 – Advanced Programming Concepts
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Polymorphism 2nd Lecture CMSC 202 Polymorphism 2nd Lecture

Topics Constructors and polymorphism The clone method Abstract methods Abstract classes Aug 6, 2007

Constructors and Polymorphism A constructor for the base class is automatically called during construction of a derived class. This call propagates up the inheritance hierarchy until the constructor for every base class is called. Why does this make sense? The constructor’s job is to see that the object is completely built. The derived class cannot have access to the base class’ private instance variables. The base class constructor must be called to initialize its instance variables. Therefore, all base class constructors must be called to fully initialize the entire derived class object. Aug 6, 2007

More Dogs public class Animal { public Animal( ) {System.out.println(“Animal”); } } public class Dog extends Animal public Dog( ) {System.out.println(“Dog”); } public class Poodle extends Dog public Poodle( ) {System.out.println(“Poodle”);} public class Collie extends Dog { public Collie( ) {Sytem.out.println( “Collie”);} public class Cage { public Cage( ) { System.out.println(“Cage”);} } public class Zoo extends Cage { public Zoo( ) { System.out.println(“Zoo”); } Aug 6, 2007

DogKennel Cage Zoo Animal Dog Poodle Collie DogKennel public class DogKennel extends Zoo { private Poodle harry = new Poodle( ); private Collie lassie = new Collie( ); public DogKennel( ) { System.out.println( “DogKennel”); } public static void main (String[ ] args) { DogKennel kennel = new DogKennel( ); } } //--- Output --- Cage Zoo Animal Dog Poodle Collie DogKennel Aug 6, 2007

Order of Construction Note that base class constructors are called implicitly if there is no explicit call super( ); Base class constructors, recursively from the top of the hierarchy Instance variables in order of declaration The body of the derived class constructor Aug 6, 2007

Copyright © 2008 Pearson Addison-Wesley. Order of Execution The stages of instance initialization are: (numbering not important: ordering is!) Stage 1: space allocated on heap Stage 2: All instance variables, direct and inherited, initialized to default values Stage 3: Constructor for requested class initiated [N] Version 10/09 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 7

Copyright © 2008 Pearson Addison-Wesley. Order of Execution Stage 4: Call to this(…) or super(…) executed first Recall: all constructors must start with either a call to this() or implicit/explicit call to super() (except for class Object) Stage 5: After call to super(…), instance variable initializers executed next, in lexical order This is why they cannot be used as arguments to super(), or to this() Stage 6: Constructor body executed [N] Version 10/09 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 8

Derived Class Copy Constructors Derived class copy constructors must make an explicit call to the base class copy constructor. public Dog( Dog anotherDog ) { // super takes care of the base class “stuff” super( anotherDog ); // polymorphism // code specific to Dogs follows } Aug 6, 2007

A First Look at the clone Method Every object inherits a method named clone from the class Object. The method clone has no parameters. Its purpose is to return a deep copy of the calling object. However, the inherited version of the method was not designed to be used as is. Each class is expected to override it with a more appropriate version. Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 10

A First Look at the clone Method The heading for the clone method defined in the Object class is: protected Object clone() The heading for a clone method that overrides the clone method in the Object class can differ somewhat from the heading above. A change to a more permissive access, such as from protected to public, is always allowed when overriding a method definition. Changing the return type from Object to the type of the class being cloned is allowed because every class is a descendent class of the class Object. This is an example of a covariant return type. Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 11

A First Look at the clone Method If a class has a copy constructor, the clone method for that class can use it to create the copy returned by the clone method. public Animal clone() { // call Animal’s copy constructor return new Animal(this); } Another example: public Dog clone() // Dog’s copy constructor return new Dog(this); Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 12

Pitfall: Limitations of Copy Constructors The copy constructor and clone method for a class appear to do the same thing. However, there are cases where only a clone will work. Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 13

Cloning a Zoo public class Zoo { Animal[ ] animals = new Animal[3]; public Zoo( ) { animals[0] = new Dog( ); animals[1] = new Cat( ); animals[2] = new Pig( ); } // incorrect copy constructor – why? public Zoo( Zoo z ) animals = new Animal[3]; for (int k = 0; k < 3; k++) animals[ k ] = new Animal( z.animals[ k ] ); } Aug 6, 2007

Pitfall: Limitations of Copy Constructors The statement animals[ k ] = new Animal( z.animals[ k ]); only copies the base class (Animal) part of each animal, not the specific stuff in each derived class We need to call the copy constructor for the derived class to make an appropriate deep copy, but copy constructors must be called by name, and we don’t know what kind of animal is really stored in each element of the array If the clone method is used instead of the copy constructor, then (because of polymorphism) a true copy is made, even from objects of a derived class (e.g., Dog, Cat, Pig). The correct statement is animals[ k ] = z.animals[ k ].clone( ) ; Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 15

Complexities and Issues with clone() Object.clone() does shallow field copies Option 2: call super.clone() first to get shallow copy, then modify specific reference fields. Object.clone() implementation will throw CloneNotSupportedException if class does not explicitly implement Cloneable interface So, you cannot call super.clone() from just any class clone() inherits to all children Once declared “public”, cannot be “disabled” in any descendent class [TD: revise to highlight super.clone()- Object using reflection to create most specific class (MSC) If we follow this convention, then we are guaranteed clone() + polymorphism will at least create correct class inst, and consequence of not overriding is merely not deep-copying subclass-specific fields. If we use the [orig. 202 procedure], then we must call specific constructor, so inheriting will lead to error.] Aug 6, 2007

Introduction to Abstract Classes public class Employee { private String name; private Date hireDate; // constructors, accessors, mutators, equals, toString } public class HourlyEmployee extends Employee private double wageRate; private double hours; //for the month public double getPay( ) {return wageRate * hours;} public class SalariedEmployee extends Employee private double salary; //annual public double getPay() { return salary / 12; } Aug 6, 2007

samePay Suppose that we decide that it will often be necessary to determine if two Employees have the same pay. We decide to implement a method named samePay in the Employee class. This method should be able to compare the pays for any kinds of Employees. public boolean samePay(Employee other) { return(this.getPay() == other.getPay()); } Aug 6, 2007

Problem with samePay The method samePay calls getPay. Solution: While getPay is defined for SalariedEmployees and HourlyEmployees, there is no meaningful implementation of getPay for a generic Employee. We can’t implement getPay without knowing the type of Employee. Solution: Require that classes derived from Employee (who know what type they are) implement a suitable getPay method that can then be used from samePay. Java provides this capability through the use of abstract methods. Aug 6, 2007

Introduction to Abstract Classes An abstract method is like a placeholder for a method that will be fully defined in a descendent class. It postpones the definition of a method. It has a complete method heading to which the modifier abstract has been added. It cannot be private. It has no method body, and ends with a semicolon in place of its body. public abstract double getPay(); public abstract void doIt(int count); The body of the method is defined in the derived classes. The class that contains an abstract method is called an abstract class. Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 20

Copyright © 2008 Pearson Addison-Wesley. Abstract Class A class that has at least one abstract method is called an abstract class. An abstract class must have the modifier abstract included in its class heading. public abstract class Employee { private instanceVariables; . . . public abstract double getPay(); } Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 21

Copyright © 2008 Pearson Addison-Wesley. Abstract Class An abstract class can have any number of abstract and/or fully defined methods. If a derived class of an abstract class adds to or does not define all of the abstract methods, it is abstract also, and must add abstract to its modifier. A class that has no abstract methods is called a concrete class. Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 22

Abstract Employee Class public abstract class Employee { private String name; private Date hireDate; public abstract double getPay( ); // constructors, accessors, mutators, equals, toString public boolean samePay(Employee other) return(this.getPay() == other.getPay()); } Aug 6, 2007

Pitfall: You Cannot Create Instances of an Abstract Class An abstract class can only be used to derive more specialized classes. While it may be useful to discuss employees in general, in reality an employee must be a salaried worker or an hourly worker An abstract class constructor cannot be used to create an object of the abstract class. However, a derived class constructor will include an invocation of the abstract class constructor in the form of super. Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 24

An Abstract Class Is a Type Although an object of an abstract class cannot be created, it is perfectly fine to have a parameter of an abstract class type. This makes it possible to plug in an object of any of its descendent classes. It is also fine to use a variable of an abstract class type, as long is it names objects of its concrete descendent classes only. Aug 6, 2007 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 25

Additional Topics/Questions Are constructors inherited? What happens when a child redefines an instance variable? Variables do not overload or override: they “hide” What happens if: parent: “public int x”, child: “public String x” parent: “public int x:, child: “private int x”  then: child-of-child: “x = 42” Do private methods inherit/obey polymorphism? Can a child class define a private method with the same signature as an inherited method? Aug 6, 2007

Additional Topics/Questions What happens when a parent’s method is called? Recall: parent method can be triggered through inheritance, or via super.someMethod() What happens w/call to myOverriddenMethod() in parent? What happens w/call to private method in parent? …when child has same-named private method? …when child has same-named public method? Aug 6, 2007