Chapter 9 Polymorphism and Inheritance Starting Out with































































- Slides: 63

Chapter 9: Polymorphism and Inheritance Starting Out with Java: Early Objects Third Edition as modified for CSCI 1260 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter Topics Chapter 9 discusses the following main topics: o What Is Inheritance? o Calling the Superclass Constructor o Overriding Superclass Methods o Protected Members o Chains of Inheritance o The Object Class o Polymorphism o Abstract Classes and Abstract Methods o Interfaces Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -2

What is Inheritance? Generalization vs. Specialization • Real-life objects are typically specialized versions of other more general objects. o An Employee is-a specialized Person Stude nt o A Carpenter is-a specialized Person o A Car is-a specialized Conveyance o A Bus is-a specialized Conveyance o An Airplane is-a specialized Conveyance Employ ee Carpente r Person o A Student is-a specialized Person o A Moped is-a specialized Conveyance Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -3

The “is-a” Relationship • We can extend the capabilities of a class. • Inheritance involves a superclass and a subclass o The superclass is the general class o The subclass is the specialized class • The subclass is based on, on or extended from, from the superclass o Superclasses are also called base classes o Subclasses are also called derived classes • Superclasses and subclasses can be thought of as parent classes and child classes Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -4

Inheritance • The subclass inherits fields and methods from the superclass without any of them having to be rewritten • New fields and new methods may be added to the subclass • The Java keyword, extends is used on the class header to define the subclass public class Student extends Person New derived class - subclass Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Base class – superclass 9 -5

Inheritance in Astah/UML Drag from Child to Parent to get … … this Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -6

The Person/Student Example Contains attributes and methods applicable to all Persons UML Inheritance (is-a) indicator Has attributes and methods needed to make Students special types of Persons; inherits methods, attributes from Person Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -7

Inheritance, Fields and Methods • private members of the superclass: superclass o Are not inherited by the subclass in the sense that the subclass cannot access them directly o Do exist in memory when the object of the subclass is created o May be accessed from the subclass but only by using the public methods of the superclass • Members of the superclass that are public: public o Are inherited by the subclass o May be accessed directly within the subclass Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -8

Inheritance, Fields, and Methods • When an instance of the subclass is created, created the non-private methods of the superclass are available through the subclass object • Non-private methods and fields of the superclass are available directly in the subclass Parent class methods Child class methods Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -9

Inheritance and Constructors • Constructors are not inherited • However, when a subclass is instantiated, instantiated the superclass default constructor is executed first – before the constructor for the derived class o We must have an object of the parent class before we can specialize it and turn it into an object of the child class Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -10

Using the Parent Constructor from Child Constructor • The child class’s constructor may use the parent class’s constructor to initialize fields inherited from the parent • The super keyword refers to an object’s superclass • The superclass constructor can be explicitly called from the subclass by using the super keyword • If the subclass constructor invokes the superclass constructor using super, super it must be first in the subclass constructor Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -11

The Superclass’s Constructor Invokes the default constructor of the parent class (Person) Person Both Student constructors initialize the attributes Student adds to Person Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Invokes the nondefault constructor of the parent class (Person) Person and lets it initialize inherited attributes 9 -12

Calling The Superclass Constructor • If a parameterized constructor is defined in the superclass, superclass either o The superclass must provide a no-argument constructor, constructor or o Subclasses must provide a constructor, constructor and the subclasses’ constructors must call a superclass constructor • Calls to a superclass constructor must be the first java statement in the subclass constructors o This is true because since a subclass object IS A superclass object, we must have the superclass object before we can specialize it to become the subclass object o Example: we must have a Person before we can add a major, major GPA, GPA class schedule, schedule etc to turn the Person into a Student Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -13

Overriding Superclass Methods • A subclass may have a method with the same signature as a superclass method • The subclass method overrides the superclass method • This is known as method overriding • This may be useful when the subclass method needs to do something more or something different than the superclass method with the same name Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -14

Overriding Superclass Methods This method in the Parent class is overridden in the child class below This method overrides the one with the same signature in Person above Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -15

Overriding Superclass Methods • Recall that a method’s signature consists of: o the method’s name o the data types of the method’s parameters in the order that they appear • A subclass method that overrides a superclass method must have the same signature as the superclass method • An object of the subclass invokes the subclass’s version of the method, method not the superclass’s version Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -16

Overriding Superclass Methods • A subclass method can call the overridden superclass method via the super keyword Parent class version called to do part of work • There is a distinction between overloading a method and overriding a method • With overloading, overloading a method has the same name as one or more other methods, but with a different signature • When a method overrides another method, method however, they both have the same signature Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -17

Overriding Superclass Methods • Both overloading and overriding may take place in an inheritance relationship • Overriding can only take place in an inheritance relationship • See example on next slide Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -18

Example: overloading and overriding Overload in same class Overrides method defined on lines 7 -11 of Super. Class 3 Another overload of the method with same name in both Super. Class 3 and Sub. Class 3 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -19

Java Packages • In Java, one may group related classes into a package o Scanner is one class in the java. util package o Some other frequently used packages include • java. io • javax. swing • java. lang • java. text • An individual class may be imported from a package using something similar to the following import java. util. Scanner; • One may also import all classes in a package using a technique such as (the asterisk acts as a wildcard) import java. util. *; Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -21

Protected Members • Java provides a third access specification, specification protected • Protected members of class: o may be accessed by methods in a subclass o by methods in the same package as the class • A protected member’s access is somewhere between private and public Making these protected rather than private allows derived classes to access them directly Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -22

Protected Members • Using protected instead of private makes some tasks easier • However, any class that is derived from the class, class AND any class that is in the same package, package has unrestricted access to the protected member – just as if it were public • It is always better to make all fields private and then provide public methods for accessing those fields • If no access specifier for a class member is provided, the class member is given package access by default o Any method in the same package may access the member Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -23

Access Specifiers Accessible to a subclass inside the same package? Accessible to all other classes inside the same package? default (no modifier) Yes Public Yes Protected Yes Private No No Accessible to a subclass outside the package? Accessible to all other classes outside the package? default (no modifier) No No Public Yes Protected Yes No Private No No Access Modifier Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -24

Chains of Inheritance • A superclass can, itself, be derived from another class Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -25

The Object Class • All Java classes are directly or indirectly derived from a class named Object o It is “weird” weird to have a class named Object since an object is an instance of a class, but this is the way the designers of Java decided to name the class named Object so we live with it • Object is in the java. lang package so it is always available without having to import anything • Any class that does not specify the extends keyword is automatically derived directly from the Object class public class My. Class { } //this class is derived from Object • Ultimately, every class is derived from the Object class Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -26

The Object Class • Because every class is directly or indirectly derived from the Object class: o Every class inherits the Object class’s non-private members • Examples: the to. String and equals are inherited by every class • In the Object class, the to. String method returns a string containing the object’s class name and a hash of its memory address • The equals method accepts a reference (the address of) to an object as its argument and returns true if it refers to the same as the calling object’s address • Example: Object. Methods. java Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -27

Example Output: Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -28

Is-a Relationship in Inheritance Hierarchy Object is-a Person is-a Undergrad is-a Employee Student is-a Grad is-a Hourly Customer is-a Salaried is-a Preferred is-a Part-time Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -29

Is-a Relationship in Inheritance Object is-a Shape is-a Ellipse 4 -sided Triangle is-a Rectangle is-a Rhombus Right is-a Circle Square Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -30

Several Types of Polymorphism POLYMORPHISM Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -31

Types of Polymorphism • Three primary types of polymorphism are discussed here o Ad-hoc o Subtype o Parametric Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -32

Method Overloading AD-HOC POLYMORPHISM Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -33

Ad-Hoc Polymorphism • Reading: Gaddis, Chapter 6 • Ad-hoc polymorphism refers to method overloading • In method overloading, “two or more methods in a single class may have the same name as long as their signatures are different” different • This was covered in 1250 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -34

Overloading methods - example Output produced: addition and then concatenation from lines 6 and 7 Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -35

Inheritance and the ISA relationship SUBTYPE POLYMORPHISM Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -36

Subtype Polymorphism • Since an object of a subclass “is-a” object of its superclass (a Student object is-a Person object), a reference variable of the superclass can reference objects of its subclasses Person josh; • We can use the josh variable to reference a Person object josh = new Person(); • The Person class is the superclass for the Student class so o An object of the Student class is a Person object josh = new Student(); Declared to be a Person object Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley josh is an object of Person but it can refer to a Student because a Student is-a Person 9 -37

Polymorphism • A Person reference can be used to reference a Student object (or any other type that extends Person) Person josh = new Student( ); • This statement creates a Student object and stores the object’s address in the josh variable • This is an example of subtype polymorphism • In Java, a reference variable is polymorphic because it can reference objects of types different from its own, as long as those types are subclasses of its type because of the is-a relationship between a subclass and its parent class • The Musical. Instrument example in the next section will help to clarify the value of subtype polymorphism Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -38

Polymorphism and Dynamic Binding • If the object of a subclass that has overridden a method in the superclass and o If the object makes a call to that method, the subclass’s version of the method will be the one that is executed Person lisa = new Student ( ); System. out. println( lisa. to. String( )); • Java performs dynamic binding or late binding when a variable contains a polymorphic reference o This means that the Java Virtual Machine determines at runtime which method to call, depending on the actual type of object that the variable references at that time Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -39

Polymorphism • It is the object’s type, type rather than the reference type, type that determines which method is called Reference refers to Actual object in memory • Note that a derived object is a base object The converse is NOT true o You cannot assign a superclass object to a subclass reference variable Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -40

Polymorphism and Typecasting • If we have the situation on the previous two slides, but we want to invoke a method from the child class only, we have to typecast the object because it is defined as a base class object: typecasts affect the object only in the current expression – not in the rest of the code The typecast says please treat the Person willie as a Student because I know he really is one Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -41

Useful operations • An object of any class in this diagram is-a Shape o If one has a Shape, Shape it may be useful to know what specific shape it is (is it a Circle, Circle Square, Square Triangle, Triangle …? ) o Use the instanceof operator Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -42

Useful operations • In the preceding slide, one may want to display the name of the class that the object s represents rather than asking a question about what type of object it is • If so, use this type of operation: Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -43

Generics PARAMETRIC POLYMORPHISM Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -44

Parametric Polymorphism • Reading: Gaddis, Chapter 7 • Parametric polymorphism refers to passing the name of a data type as an argument to a class thereby creating a new data type o This requires a special type of class that accepts such an argument (called a generic class) class o Recall the Array. List class used in an earlier example: the Person class was passed to Array. List as a parameter creating a new type named Array. List <Person> o This indicates what type of data the Array. List contains Array. List <Person> persons = new Array. List <Person> ( ); Array. List <Shape> shapes = new Array. List <Shape> ( ); Array. List <Parking. Meter> meters = new Array. List <Parking. Meter> ( ); Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -45

Abstract classes and abstract methods ABSTRACT CLASSES Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -46

Abstract Classes • An abstract class is an incompletely defined class – some or all methods may lack their implementation • One may not instantiate objects of an abstract class, but other classes may be derived from it • An abstract class only serves as a superclass for other classes • The abstract class represents the generic or abstract form of all the classes that are derived from it • A class becomes abstract when you place the abstract key word in the class definition public abstract class Class. Name Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -47

Abstract Methods • In a base class, class a method may be too difficult to implement for a very general case while it may be easier to implement it in a more specific case in a derived class o For example, for a generic Shape, Shape it may be very difficult to calculate its area, area but for a specific derived class such as Rectangle, Rectangle calculating the area is easy because there is a wellknown formula for doing so o Using an abstract method allows one to postpone the implementation until the derived class when implementing the method may be much easier Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -48

Abstract Methods • An abstract method appears in a superclass, superclass but it has no implementation and must be overridden in a subclass • An abstract method has only a header, header but no body public abstract Return. Type Method. Name( Parameter. List ); The word abstract tells Java that this method has no body and asks Java to allow that to compile without an error. Trying to create an object of the containing class would be an error, however, since the class is incomplete – this method has no body. Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Note the semicolon – no open brace follows 9 -49

Abstract Methods • Notice that the key word abstract appears in the header, header and that the header ends with a semicolon public abstract void set. Value(int value); • Any class that contains an abstract method is automatically an abstract class • If a subclass fails to override an abstract method, a compile-time error will result Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -50

Abstract Class with Abstract Methods-Example Abstract class An abstract class may have some concrete methods … … and some abstract methods Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -51

Making a concrete class from abstract class Abstract method is fully defined in the derived class, making it a concrete method Abstract method is fully defined Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -52

Using the Concrete Classes Subtype polymorphism in action with an abstract class Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -53

Contracting to implement specific methods JAVA INTERFACES Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -54

Subtype Polymorphism - Interfaces • In Java, sub-type polymorphism is not limited to an inheritance hierarchy, hierarchy it also applies to interfaces • An interface is similar to an abstract class that has only abstract methods o It cannot be instantiated, and o All implementations of the methods listed in an interface must be written elsewhere • The purpose of an interface is to specify behavior that is shared by multiple classes • An interface looks similar to a class, class except: o The keyword interface is used instead of the keyword class, and o The methods that are specified in an interface have no bodies, only headers that are terminated by semicolons Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -55

Interfaces • The general format of an interface definition: Example of parametric polymorphi sm • All methods specified by an interface are public by default • A class can implement one or more interfaces • This is a generic interface as indicated by the place-holder type T; this is an example of parametric polymorphism Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -56

Interfaces • If a class implements an interface, it uses the implements keyword in the class header • It may also make the type specific for a generic type Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -57

Fields in Interfaces • An interface can contain field declarations: declarations o All fields in an interface are treated as final and static • Because fields automatically become final, final you must provide an initialization value public interface Doable <T> { final int FIELD 1 = 1, FIELD 2 = 2; (Method headers go here. . . ) } • In this interface, interface FIELD 1 and FIELD 2 are final static int variables • Any class that implements this interface has access to these variables Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -58

Implementing Multiple Interfaces • A class may be derived directly from only one superclass o That is, a class may have only one immediate parent class • Java allows a class to implement multiple interfaces • When a class implements multiple interfaces, interfaces it must implement all of the methods specified by all of the interfaces • To specify multiple interfaces in a class definition, simply list the names of the interfaces, interfaces separated by commas, commas after the implements keyword public class My. Class implements Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Interface 1, Interface 2, Interface 3 9 -59

Interfaces in UML A dashed line with an arrow indicates implementation of an interface. Also called “realization” Because Person implements Comparable and because Employee is derived from Person, Employees are also Comparable Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -60

Polymorphism with Interfaces • Java allows you to create reference variables of an interface type • An interface reference variable can reference any object that implements that interface, interface regardless of its class type • See the next slide for more discussion on this issue Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -61

How does an interface help? • Suppose we need to sort Students, Persons, Accounts, Routes, Customers, Products, etc. o It would be helpful not to have to write a separate sort method for each different type of thing to sort public void sort (Student [ ] students) … public void sort (Person [ ] people) … public void sort (Product [ ] products) … o If each of these classes implements the Comparable interface, we can write one method to sort ALL of the different types (i. e. , we can sort any types of things that are Comparable) Comparable public void sort (Comparable [ ] things) … o If the classes mentioned in the first bullet above all implement the Comparable interface, arrays of any of them can be sorted sort with the single sort method above – without having to have a different method for each type • That is we can sort any types of things that we can compare • We cannot use this method to sort anything we cannot compare Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley January 24, 2022

Interface example Continued on the next slide … Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -63

Interface Example The term “<T extends Comparable<T>>” Comparable<T>> should be read as “any type T that implements Comparable<T> This method can sort an array of any data type T as long as T implements Comparable<T> Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 -64