1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses...

40
1 Object-Oriented Object-Oriented Programming Programming Inheritance Inheritance

description

3 Inheritance hierarchy for university CommunityMember s. CommunityMember EmployeeStudent StaffFaculty AdministratorTeacher Alumnus

Transcript of 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses...

Page 1: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

11

Object-Oriented ProgrammingObject-Oriented Programming Inheritance Inheritance

Page 2: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

22

Superclasses and SubclassesSuperclasses and Subclasses Superclasses and subclassesSuperclasses and subclasses

Object of one class “is an” object of another classObject of one class “is an” object of another class• Example: Rectangle is quadrilateral.Example: Rectangle is quadrilateral.

Class Class RectangleRectangle inherits from class inherits from class QuadrilateralQuadrilateral QuadrilateralQuadrilateral: superclass: superclass RectangleRectangle: subclass: subclass

Superclass typically represents larger set of objects Superclass typically represents larger set of objects than subclassesthan subclasses• Example: Example:

superclass: superclass: VehicleVehicle• Cars, trucks, boats, bicycles, …Cars, trucks, boats, bicycles, …

subclass: subclass: CarCar• Smaller, more-specific subset of vehiclesSmaller, more-specific subset of vehicles

Page 3: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

33

Inheritance hierarchy for university CommunityMembers.

CommunityMember

Employee Student

StaffFaculty

Administrator Teacher

Alumnus

Page 4: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

44

Inheritance hierarchy for Shapes.

Shape

TwoDimensionalShape ThreeDimensionalShape

Circle Square Triangle Sphere Cube Tetrahedron

Page 5: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

55

Superclasses and Subclasses Superclasses and Subclasses (Cont.)(Cont.)

Inheritance examplesInheritance examplesSuperclass Subclasses Student GraduateStudent,

UndergraduateStudent Shape Circle, Triangle, Rectangle Loan CarLoan, HomeImprovementLoan,

MortgageLoan Employee Faculty, Staff BankAccount CheckingAccount,

SavingsAccount Inheritance examples.

Page 6: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

66

Superclasses and Subclasses Superclasses and Subclasses (Cont.)(Cont.)

Inheritance hierarchyInheritance hierarchy Inheritance relationships: tree-like hierarchy Inheritance relationships: tree-like hierarchy

structurestructure Each class becomesEach class becomes

• superclasssuperclass Supply data/behaviors to other classesSupply data/behaviors to other classes

OROR• subclasssubclass

Inherit data/behaviors from other classesInherit data/behaviors from other classes

Page 7: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

77

Superclasses and SubclassesSuperclasses and Subclasses GeometricObject

-color: String -filled: boolean -dateCreated: java.util.Date

+GeometricObject() +getColor(): String +setColor(color: String): void +isFilled(): boolean +setFilled(filled: boolean): void +getDateCreated(): java.util.Date +toString(): String

The color of the object (default: white). Indicates whether the object is filled with a color (default: false). The date when the object was created.

Creates a GeometricObject. Returns the color. Sets a new color. Returns the filled property. Sets a new filled property. Returns the dateCreated. Returns a string representation of this object.

Circle -radius: double

+Circle() +Circle(radius: double) +getRadius(): double +setRadius(radius: double): void +getArea(): double +getPerimeter(): double +getDiameter(): double

Rectangle -width: double -height: double

+Rectangle() +Rectangle(width: double, height: double) +getWidth(): double +setWidth(width: double): void +getHeight(): double +setHeight(height: double): void +getArea(): double +getPerimeter(): double

GeometricObject

Circle

Rectangle

TestCircleRectangle

Page 8: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

88

Are superclass’s Constructor Are superclass’s Constructor Inherited?Inherited?

No. They are not inherited.

They are invoked explicitly or implicitly.

Explicitly using the super keyword.

A constructor is used to construct an instance of a class. Unlike properties and methods, a superclass's constructors are not inherited in the subclass. They can only be invoked from the subclasses' constructors, using the keyword super. If the keyword super is not explicitly used, the superclass's no-arg constructor is automatically invoked.

Page 9: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

99

Superclass’s Constructor Is Always Superclass’s Constructor Is Always InvokedInvoked

A constructor may invoke an overloaded constructor or A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked its superclass’s constructor. If none of them is invoked explicitly, the compiler puts explicitly, the compiler puts super()super() as the first statement as the first statement in the constructor. For example,in the constructor. For example,

public A(double d) { // some statements }

is equivalent to

public A(double d) { super(); // some statements }

public A() { }

is equivalent to

public A() { super(); }

Page 10: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1010

Using the Keyword Using the Keyword supersuper

To call a superclass constructorTo call a superclass constructor To call a superclass methodTo call a superclass method

The keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways:

Page 11: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1111

CAUTIONCAUTION

You must use the keyword super to call the superclass constructor. Invoking a superclass constructor’s name in a subclass causes a syntax error. Java requires that the statement that uses the keyword super appear first in the constructor.

Page 12: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1212

Constructor ChainingConstructor Chaining

public class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining.

Page 13: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1313

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

1. Start from the main method

Page 14: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1414

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

2. Invoke Faculty constructor

Page 15: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1515

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

3. Invoke Employee’s no-arg constructor

Page 16: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1616

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

4. Invoke Employee(String) constructor

Page 17: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1717

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

5. Invoke Person() constructor

Page 18: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1818

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

6. Execute println

Page 19: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

1919

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

7. Execute println

Page 20: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2020

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

8. Execute println

Page 21: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2121

Trace ExecutionTrace Executionpublic class Faculty extends Employee { public static void main(String[] args) { new Faculty(); } public Faculty() { System.out.println("(4) Faculty's no-arg constructor is invoked"); }} class Employee extends Person { public Employee() { this("(2) Invoke Employee’s overloaded constructor"); System.out.println("(3) Employee's no-arg constructor is invoked"); }  public Employee(String s) { System.out.println(s); }} class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); }}

9. Execute println

Page 22: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2222

Example on the Impact of a Superclass Example on the Impact of a Superclass without no-arg Constructorwithout no-arg Constructor

public class Apple extends Fruit {} class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); }}

Find out the errors in the program:

Page 23: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2323

Declaring a SubclassDeclaring a SubclassA subclass extends properties and A subclass extends properties and methods from the superclass. You can methods from the superclass. You can also:also: Add new properties (Seen already)Add new properties (Seen already)

Add new methods (Seen already)Add new methods (Seen already)

Override the methods of the superclass (to Override the methods of the superclass (to be discussed)be discussed)

Page 24: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2424

Calling Superclass MethodsCalling Superclass MethodsYou could rewrite the printCircle() method in the Circle class as follows:

public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius);}

Page 25: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2525

Overriding Methods in the Overriding Methods in the SuperclassSuperclass

A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. This is referred to as method overriding.

public class Circle extends GeometricObject {

// Other methods are omitted

/** Override the toString method defined in GeometricObject */ public String toString() { return super.toString() + "\nradius is " + radius; }

}

Page 26: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2626

NOTENOTE

An instance method can be overridden only if it is accessible. Thus a private method cannot be overridden, because it is not accessible outside its own class. If a method defined in a subclass is private in its superclass, the two methods are completely unrelated.

Page 27: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2727

NOTENOTE

Like an instance method, a static method can be inherited. However, a static method cannot be overridden. If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden.

Page 28: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2828

Overriding vs. OverloadingOverriding vs. Overloading

public class Test { public static void main(String[] args) { A a = new A(); a.p(10); } } class B { public void p(int i) { } } class A extends B { // This method overrides the method in B public void p(int i) { System.out.println(i); } }

public class Test { public static void main(String[] args) { A a = new A(); a.p(10); } } class B { public void p(int i) { } } class A extends B { // This method overloads the method in B public void p(double i) { System.out.println(i); } }

Page 29: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

2929

The The ObjectObject Class ClassEvery class in Java is descended from the Every class in Java is descended from the java.lang.Objectjava.lang.Object class. If no inheritance is class. If no inheritance is specified when a class is defined, the specified when a class is defined, the superclass of the class is superclass of the class is ObjectObject. .

public class Circle { ... }

Equivalent public class Circle extends Object { ... }

Page 30: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3030

The toString() method in The toString() method in ObjectObject

The The toString()toString() method returns a string representation of the method returns a string representation of the object. The object. The default implementation returns a string consisting default implementation returns a string consisting of a class name of which the object is an instance, the at sign of a class name of which the object is an instance, the at sign (@), and a number representing this object.(@), and a number representing this object.

Loan loan = new Loan();Loan loan = new Loan();System.out.println(loan.toString());System.out.println(loan.toString());

The code displays something like The code displays something like Loan@15037e5Loan@15037e5 .. This message is not very helpful or informative. Usually you This message is not very helpful or informative. Usually you should override the should override the toStringtoString method so that it returns a method so that it returns a digestible string representation of the object.digestible string representation of the object.

Page 31: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3131

Object-Oriented Programming: Object-Oriented Programming: PolymorphismPolymorphism

Page 32: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3232

The The protectedprotected Modifier Modifier The The protectedprotected modifier can be applied on data modifier can be applied on data

and methods in a class. A protected data or a and methods in a class. A protected data or a protected method in a public class can be protected method in a public class can be accessed by any class in the same package accessed by any class in the same package (folder) or its subclasses, even if the subclasses (folder) or its subclasses, even if the subclasses are in a different package.are in a different package.

private, default, protected, publicprivate, default, protected, public

private, none (if no modifier is used), protected, public

Visibility increases

Page 33: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3333

Accessibility SummaryAccessibility 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 - - -

Page 34: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3434

Visibility Modifiers Visibility Modifiers

public class C1 { public int x; protected int y; int z; private int u; protected void m() { } }

public class C2 { C1 o = new C1(); can access o.x; can access o.y; can access o.z; cannot access o.u; can invoke o.m(); }

public class C3 extends C1 { can access x; can access y; can access z; cannot access u; can invoke m(); }

package p1;

public class C4 extends C1 { can access x; can access y; cannot access z; cannot access u; can invoke m(); }

package p2;

public class C5 { C1 o = new C1(); can access o.x; cannot access o.y; cannot access o.z; cannot access o.u; cannot invoke o.m(); }

Page 35: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3535

A Subclass Cannot Weaken the A Subclass Cannot Weaken the AccessibilityAccessibility

A subclass may override a protected method in its superclass and change its visibility to public. However, a subclass cannot weaken the accessibility of a method defined in the superclass. For example, if a method is defined as public in the superclass, it must be defined as public in the subclass.

Page 36: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3636

NOTENOTE

The modifiers are used on classes and class members (data and methods), except that the final modifier can also be used on local variables in a method. A final local variable is a constant inside a method.

Page 37: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3737

The The finalfinal Modifier Modifier The The finalfinal class cannot be extended: class cannot be extended: final class Math {final class Math { ...... }}

The The finalfinal variable is a constant: variable is a constant: final static double PI = 3.14159;final static double PI = 3.14159;

The The finalfinal method cannot be overridden by its method cannot be overridden by its subclasses.subclasses.

Page 38: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3838

The equals() and hashCode() The equals() and hashCode() Methods in the Methods in the ObjectObject Class Class

The The equals()equals() method compares the method compares thecontents of two objects. contents of two objects.

The The hashCode()hashCode() method returns the hash method returns the hash code of the object. Hash code is an code of the object. Hash code is an integer, which can be used to store the integer, which can be used to store the object in a hash set so that it can be object in a hash set so that it can be located quickly. located quickly.

Nice to knowNice to know

Page 39: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

3939

The The equals equals MethodMethodThe The equals()equals() method compares the method compares thecontents of two objects. contents of two objects. The default implementation of the The default implementation of the equals method in the Object class is as follows:equals method in the Object class is as follows:

public boolean equals(Object obj) {public boolean equals(Object obj) {

return (this == obj);return (this == obj);}}

For example, the For example, the equals method is equals method is overridden in overridden in the Circle the Circle class.class.

public boolean equals(Object o) {public boolean equals(Object o) { if (o instanceof Circle) {if (o instanceof Circle) { return radius == ((Circle)o).radius;return radius == ((Circle)o).radius; }} elseelse return false;return false;}}

Nice to knowNice to know

Page 40: 1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.

4040

NOTENOTE•The “==”comparison operator is used for comparing two primitive data type values or for determining whether two objects have the same references. •The “equals” method is intended to test whether two objects have the same contents, provided that the method is modified in the defining class of the objects. The == operator is stronger than the equals method, in that the == operator checks whether the two reference variables refer to the same object.