Inheritance and PolymorphismChapter 11
Exam week: May 7 – 11covers until Wednesday’s lecture (Chap 9, 10,
11 and some of Chap 13)Your own cheat sheetBe sure to submit all the homework! (by May
14)
Revisited: Why OOP? The definition of a class is reusable.It is possible to define subclasses to inherit
some or all of the main class characteristics.Person Student, Teacher
The concept of data classes allows a programmer to create any new data type that is not already defined in the language itself.
Superclasses and SubclassesOOP allows you to derive new classes from
existing classes – inheritance.Inheritance enables you to define a general
class (superclass, parent class) and later extend it to more specialized classes (subclasses, child classes).
A subclass inherits accessible data fields and methods from its superclass, and may add new data fields and methods.
Employee -office: String -salary: int + Employee (name: String,
phoneNumber: String, email: String, office: String, salary: int)
+ Employee (office: String, salary: int) +Employee() +getOffice(): String +setOffice(office: String): void +getSalary (): String +setSalary(salary: int): void +printInfo(): void
Faculty -department: String -rank: String +Faculty(name: String, phoneNumber:
String, email: String, office: String, salary: int, department: String, rank: String)
+Faculty(department: String, rank: String) +getDepartment(): String +setDepartment(department: String): void +getRank(): String +setRank(rank: String): void +printInfo(): void
Staff -title: String +Staff(name: String, phoneNumber:
String, email: String, office: String, salary: int, title: String)
+Staff(title: String) +getTitle(): String +setTitle(title: String): void +printInfo(): void
Something to NoteA subclass is not a subset of its superclass.Private data fields in a superclass are not
accessible outside the class. They cannot be used directly in a subclass.
You shouldn’t define a Square class to extend a Rectangle class.
A Java class may inherit directly from only one superclass – single inheritance. Some programming languages allows multiple inheritance.
The super keywordThe keyword super refers to the superclass
of the class. To call a superclass constructorTo call a superclass method
Calling a superclass constructorYou must use the keyword super to call the
superclass constructor. super(arguments) Person(arguments) is wrong!
Java requires that the statement that uses the keyword super appear first in the constructor.
Constructor ChainingIf superclass constructor is not invoked, Java
automatically puts super() as the first statement.
Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining.
public class Person { Person() { System.out.println("Person's constructor"); }}
public class Employee extends Person { Employee() { System.out.println("Employee's constructor"); }}
public class Faculty extends Employee { Faculty() { System.out.println("Faculty's constructor"); }
public static void main(String[] args) { Faculty f1 = new Faculty(); }}
If a class is designed to be extended, it is better to provide a no-arg constructor to avoid errors!
Exercise: Create the GraduateStudent class, which inherits the Student class.Add a new data field advisor (String)Add a constructor with all customized
parametersAdd another constructor with only customized
advisorGet and set method for data field advisor
Calling superclass methodssuper.method(parameters);
Examples:super.setName(name);super.setEmail(email);
It is not necessary to use super in this case, since setName() and setEmail() are inherited by the subclass.
Overriding MethodsCreate a function printInfo() in both Person
and Student class.super is necessary here.
Overriding vs. OverloadingOverloading: multiple methods with the same
name but different signatures (number of parameters, type of parameters)
Overriding: new implementation for a method in the subclass (The method is already defined in the superclass.)
PolymorphismSubtype and supertype
Student is a subtype of PersonPerson is a supertype for Student
Every instance of a subclass is an instance of its superclass, but not vice versa.Every student is a personbut not every person is a student
You can pass an instance of a subclass (student1, student2) to a parameter of its super type (Person).
PolymorphismIn your TestPerson.java:
public static void displayObject(Person p){ ......}//Object created: Jerry
An object of a subclass can be used wherever its superclass object is used – polymorphism (“many forms”).
Dynamic BindingBoth Person and Student have the printInfo()
method.
Person p = new Student();p.printInfo();
Which printInfo() is it calling? Person’s or Student’s?
declared type vs. actual typeThe method is determined by the actual type.
The protected Data and MethodsUse the protected modifier to enable the
members of the class to be accessed by the subclasses in any package or classes in the same package.
private, none (if no modifier is used), protected, public
Visibility increases
Accessibility Summary
Modifier on members in a class
Accessed from the same class
Accessed from the same package
Accessed from a subclass
Accessed from a different package
public
protected -
default - -
private - - -
public class C1 { public int x; protected int y; int z; private int u; protected void m() { } }
public class C2 { C1 o = new C1(); o.x; o.y; o.z; o.u; o.m(); }
public class C3 extends C1 { x; y; z; u; m(); }
package p1;
public class C4 extends C1 { x; y; z; u; m(); }
package p2;
public class C5 { C1 o = new C1(); o.x; o.y; o.z; o.u; o.m(); }
The final modifierThe final variable is a constant:
public static final double PI = 3.14159;The final class cannot be extended:
public final class GraduateStudent{ ...}
The final method cannot be overridden by its subclasses:public final void printInfo(){ ....}
The ArrayList ClassOnce the array is created, its size is fixed.Add, insert, remove element in an array?ArrayList can store an unlimited number of
objects.
The ArrayList Class java.util.ArrayList
+ArrayList() +add(o: Object) : void +add(index: int, o: Object) : void +clear(): void +contains(o: Object): boolean +get(index: int) : Object +indexOf(o: Object) : int +isEmpty(): boolean +lastIndexOf(o: Object) : int +remove(o: Object): boolean +size(): int +remove(index: int) : Object +set(index: int, o: Object) : Object
Appends a new element o at the end of this list. Adds a new element o at the specified index in this list. Removes all the elements from this list. Returns true if this list contains the element o. Returns the element from this list at the specified index. Returns the index of the first matching element in this list. Returns true if this list contains no elements. Returns the index of the last matching element in this list. Removes the element o from this list. Returns the number of elements in this list. Removes the element at the specified index. Sets the element at the specified index.
Creates an empty list.
ExamplesCreate an ArrayList called cityListAdd some cities in the list: “New York,” “Chicago,” “Miami,”
“Los Angeles” What is the list size?Is Miami in the list?The location of Chicago in the list?Is the list empty?Display the contents in the listInsert San Francisco at index 2Remove Miami from the listRemove a city at index 1Display the contents in reverse orderRemove all elements
Array vs. ArrayListCreating:
int[] array = new int[10];ArrayList list = new ArrayList();
Accessing an element:array[2] list.get(2);
Updating an element:array[1] = “New York”; list.set(1, “New York”)
Returning sizearray.length list.size()
Add, insert, remove elements?
ArrayList of ObjectsBack to our Person-Student class, add
student1 and student2 to an ArrayListPrint information of the two students in the
list