Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9: Polymorphism and Inheritance

Similar presentations


Presentation on theme: "Chapter 9: Polymorphism and Inheritance"— Presentation transcript:

1 Chapter 9: Polymorphism and Inheritance
Starting Out with Java: Early Objects Third Edition as modified for CSCI 1260

2 Chapter Topics Chapter 9 discusses the following main topics:
What Is Inheritance? Calling the Superclass Constructor Overriding Superclass Methods Protected Members Chains of Inheritance The Object Class Polymorphism Abstract Classes and Abstract Methods Interfaces

3 What is Inheritance? Generalization vs. Specialization
Real-life objects are typically specialized versions of other more general objects. A Student is-a specialized Person An Employee is-a specialized Person A Carpenter is-a specialized Person A Car is-a specialized Conveyance A Bus is-a specialized Conveyance An Airplane is-a specialized Conveyance A Moped is-a specialized Conveyance Student Employee Carpenter Person

4 The “is-a” Relationship
We can extend the capabilities of a class. Inheritance involves a superclass and a subclass The superclass is the general class The subclass is the specialized class The subclass is based on, or extended from, the superclass Superclasses are also called base classes Subclasses are also called derived classes Superclasses and subclasses can be thought of as parent classes and child classes

5 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 Base class – superclass

6 Inheritance in Astah/UML
Drag from Child to Parent to get … … this

7 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

8 Inheritance, Fields and Methods
private members of the superclass: Are not inherited by the subclass in the sense that the subclass cannot access them directly Do exist in memory when the object of the subclass is created May be accessed from the subclass but only by using the public methods of the superclass Members of the superclass that are public: Are inherited by the subclass May be accessed directly within the subclass

9 Inheritance, Fields, and Methods
When an instance of the subclass is 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

10 Inheritance and Constructors
Constructors are not inherited However, when a subclass is instantiated, the superclass default constructor is executed first – before the constructor for the derived class We must have an object of the parent class before we can specialize it and turn it into an object of the child class

11 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, it must be first in the subclass constructor.

12 The Superclass’s Constructor
Invokes the default constructor of the parent class (Person) Invokes the non-default constructor of the parent class (Person) and lets it initialize inherited attributes Both Student constructors initialize the attributes Student adds to Person

13 Calling The Superclass Constructor
If a parameterized constructor is defined in the superclass, either The superclass must provide a no-argument constructor, or Subclasses must provide a 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 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 Example: we must have a Person before we can add a major, GPA, class schedule, etc to turn the Person into a Student

14 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

15 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

16 Overriding Superclass Methods
Recall that a method’s signature consists of: the method’s name 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, not the superclass’s version

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

18 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

19 Example: overloading and overriding
Overload in same class Overrides method defined on lines 7-11 of SuperClass3 Another overload of the method with same name in both SuperClass3 and SubClass3

20 Java Packages In Java, one may group related classes into a package
Scanner is one class in the java.util package 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.*;

21 Protected Members Java provides a third access specification, protected Protected members of class: may be accessed by methods in a subclass 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

22 Protected Members Using protected instead of private makes some tasks easier However, any class that is derived from the class, AND any class that is in the same 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 Any method in the same package may access the member

23 Access Specifiers Access Modifier
Accessible to a subclass inside the same package? Accessible to all other classes inside the same package? default (no modifier) Yes Public Protected Private No Access Modifier Accessible to a subclass outside the package? Accessible to all other classes outside the package? default (no modifier) No Public Yes Protected Private

24 Chains of Inheritance A superclass can, itself, be derived from another class

25 The Object Class All Java classes are directly or indirectly derived from a class named Object It is “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 MyClass { //this class is derived from Object } Ultimately, every class is derived from the Object class

26 The Object Class Because every class is directly or indirectly derived from the Object class: Every class inherits the Object class’s non-private members Examples: the toString and equals are inherited by every class In the Object class, the toString 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: ObjectMethods.java

27 Example Output:

28 Is-a Relationship in Inheritance Hierarchy
Object is-a Person is-a is-a is-a is-a Student Employee Customer is-a is-a is-a is-a is-a Undergrad Grad Hourly Salaried Preferred is-a Part-time

29 Is-a Relationship in Inheritance
Object is-a Shape is-a is-a is-a Triangle 4-sided Ellipse is-a is-a is-a is-a Rhombus Rectangle Right is-a Circle Square

30 Several Types of Polymorphism

31 Types of Polymorphism Three primary types of polymorphism are discussed here Ad-hoc Subtype Parametric

32 Method Overloading Ad-Hoc Polymorphism

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” This was covered in 1250

34 Overloading methods - example
Output produced: addition and then concatenation from lines 6 and 7

35 Inheritance and the ISA relationship
Subtype Polymorphism

36 Declared to be a Person object
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  An object of the Student class is a Person object josh = new Student(); josh is an object of Person but it can refer to a Student because a Student is-a Person Declared to be a Person object

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 MusicalInstrument example in the next section will help to clarify the value of subtype polymorphism

38 Polymorphism and Dynamic Binding
If the object of a subclass that has overridden a method in the superclass and 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.toString( )); Java performs dynamic binding or late binding when a variable contains a polymorphic reference 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

39 Actual object in memory
Polymorphism It is the object’s type, rather than the reference type, that determines which method is called Note that a derived object is a base object. The converse is NOT true You cannot assign a superclass object to a subclass reference variable Actual object in memory Reference refers to

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

41 Useful operations An object of any class in this diagram is-a Shape
If one has a Shape, it may be useful to know what specific shape it is (is it a Circle, Square, Triangle, …?) Use the instanceof operator

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:

43 ParaMetric Polymorphism
Generics ParaMetric Polymorphism

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 This requires a special type of class that accepts such an argument (called a generic class) Recall the ArrayList class used in an earlier example: the Person class was passed to ArrayList as a parameter creating a new type named ArrayList <Person> This indicates what type of data the ArrayList contains   ArrayList <Person> persons = new ArrayList <Person> ( ); ArrayList <Shape> shapes = new ArrayList <Shape> ( ); ArrayList <ParkingMeter> meters = new ArrayList <ParkingMeter> ( );

45 Abstract classes and abstract methods

46 public abstract class ClassName
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 ClassName

47 Abstract Methods In a base 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 For example, for a generic Shape, it may be very difficult to calculate its area, but for a specific derived class such as Rectangle, calculating the area is easy because there is a well- known formula for doing so Using an abstract method allows one to postpone the implementation until the derived class when implementing the method may be much easier

48 Note the semicolon – no open brace follows
Abstract Methods An abstract method appears in a superclass, but it has no implementation and must be overridden in a subclass An abstract method has only a header, but no body public abstract ReturnType MethodName( ParameterList ); 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. Note the semicolon – no open brace follows

49 Abstract Methods Notice that the key word abstract appears in the header, and that the header ends with a semicolon public abstract void setValue(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

50 Abstract Class with Abstract Methods-Example
An abstract class may have some concrete methods … … and some abstract methods

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

52 Using the Concrete Classes
Subtype polymorphism in action with an abstract class

53 Contracting to implement specific methods
Java Interfaces

54 Subtype Polymorphism - Interfaces
In Java, sub-type polymorphism is not limited to an inheritance hierarchy, it also applies to interfaces An interface is similar to an abstract class that has only abstract methods It cannot be instantiated, and 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, except: The keyword interface is used instead of the keyword class, and The methods that are specified in an interface have no bodies, only headers that are terminated by semicolons

55 Example of parametric polymorphism
Interfaces The general format of an interface definition: 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 Example of parametric polymorphism

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

57 Fields in Interfaces An interface can contain field declarations:
All fields in an interface are treated as final and static Because fields automatically become final, you must provide an initialization value public interface Doable <T> { final int FIELD1 = 1, FIELD2 = 2; (Method headers go here...) } In this interface, FIELD1 and FIELD2 are final static int variables Any class that implements this interface has access to these variables

58 Implementing Multiple Interfaces
A class may be derived directly from only one superclass 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, 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, separated by commas, after the implements keyword public class MyClass implements Interface1, Interface2, Interface3

59 Also called “realization”
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

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, regardless of its class type See the next slide for more discussion on this issue

61 How does an interface help?
Suppose we need to sort Students, Persons, Accounts, Routes, Customers, Products, etc. 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) … 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) public void sort (Comparable [ ] things) … If the classes mentioned in the first bullet above all implement the Comparable interface, arrays of any of them can be sorted 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 November 28, 2018

62 Continued on the next slide …
Interface example Continued on the next slide …

63 Interface Example The term “<T extends 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>


Download ppt "Chapter 9: Polymorphism and Inheritance"

Similar presentations


Ads by Google