Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,

Similar presentations


Presentation on theme: "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"— Presentation transcript:

1 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG, COS dept Lecture 13 Title: Inheritance in Java Reference: COS240 Syllabus

2 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 2 Lecture Contents: F To develop a subclass from a superclass through inheritance  To invoke the superclass’s constructors and methods using super keyword. F To override instance methods in the subclass. F To distinguish differences between overriding and overloading.  To explore the toString(), equals() methods in the Object class.

3 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 3 Motivations F Suppose you will define classes to model: –students, –instructors, –professors. F You can build a separate independent class for each one of the listed categories. F BUT: These classes have many common features. F What is the best way to design these classes so to avoid redundancy? The answer is to use inheritance.

4 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 4 Motivations F Suppose you will define classes to model –circles, –rectangles, –triangles. F You can build a separate independent class for each one of the listed categories (2D geometric figures). F BUT: These classes have many common features. F What is the best way to design these classes so to avoid redundancy? The answer is to use inheritance.

5 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 5 Motivations F Suppose you will define classes to model –circles, –cylinders. F You can build a separate independent class for each one of the listed categories. F BUT: These classes have many common features. F What is the best way to design these classes so to avoid redundancy? The answer is to use inheritance.

6 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 6 Motivations F Suppose you will define classes to model –rectangles, –boxes. F You can build a separate independent class for each one of the listed categories. F BUT: These classes have many common features. F What is the best way to design these classes so to avoid redundancy? The answer is to use inheritance.

7 7 What is inheritance? The OOP ability to derive new classes from existing classes. This ability is Inheritance – OR Extending Classes in Java Use keyword extends in subclass heading.

8 8 Brief presentation

9 9 Inheritance A class can inherit properties and methods from another class, called its parent. In Java, we call this extending a class. The class doing the extending is the child- or sub-class. The class getting extended is the parent or super-class. In Java, a class can only extend one parent. –No multiple inheritance like in C++. You can also: F Add new properties/attributes/data fields F Add new methods F Override the methods of the super-class

10 10 Classes form a hierarchy Classes are arranged in a treelike hierarchy. There is one class at the top, or root, of the hierarchy, named Object –In computer science we draw trees upside-down, with the root at the top! Every class except Object has one “parent” class, or super-class  single inheritance. Each class is a subclass of its super-class.

11 11 What is the class hierarchy for? Classes inherit from their super classes –A class has not only its own fields and methods, but also Every data field described in any class above it Every method described in any class above it Attention: the above field or method should be qualified as public or protected. (private qualifier makes them invisible outside their own class.) Classes do not inherit constructors, however. Hence, a class may contain much more information than is obvious from the class description

12 12 Inheritance Example public class Person { protected String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public class Student extends Person { private double accountBalance; public void increaseBalance(double amount) { this.accountBalance += amount; } public double getAccountBalance() { return accountBalance; } Here is the extends keyword, signaling inheritance ParentChild

13 13 Constructors in extended classes A constructor of the extended class can invoke one of the superclass’s constructors by using the super method in Java. If no superclass constructor is invoked explicitly, then the superclass’s default constructor is invoked automatically by the runtime system as the first statement of the extended class’s constructor. FYI: in C#, the base method is used, not super. In both C# and Java, may use base / super to invoke any overridden method in the parent class. E.g. super.ParentMethod();

14 14 Superclass public class Person{ protected String name; public Person() { name = “no_name_yet”; } public Person(String initialName) { this.name = initialName; } public String getName() { return name; } public void setName(String newName){ name = newName; } Subclass public class Student extends Person { private int studentNumber; public Student() { super(); // superclass studentNumber = 0; } public Student(String initialName, int initialStudentNumber) { super(initialName); studentNumber = initialStudentNumber; } public int getStudentNumber() { return studentNumber; } public void setStudentNumber(int newStudentNumber ) { studentNumber = newStudentNumber; }

15 15 Comprehensive presentation

16 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 16 Superclasses and Subclasses F Class is used to model objects of same type. F Different classes may have common properties/behaviors which can be generalized in a class that can be shared by other classes. F Inheritance enables you to define a general class and later extend it to more specific classes. F Consider geometric objects such as circles and rectangles – next slide

17 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 17 Superclasses and Subclasses F Geometric objects: circles and rectangles F Common properties: –Color, filled/nofilled, dateCreated F Circle – specific properties: –radius F Rectangle – specific properties: –width, height

18 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 18 Superclasses and Subclasses

19 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 19 Superclasses and Subclasses F Inheritance illustrated as skeletal Java source class GeometricObject { … } class Circle extends GeometricObject { … } class Rectangle extends GeometricObject { … } public class TestProgram { public static void main(…) { … } … }

20 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 20 class GeometricObject F Inheritance illustrated as skeletal Java source See detailed source text in file ProgGeometricObject.java

21 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 21 Task 1 F Write a Java program to illustrate the inheritance relation among classes Circle and Cylinder Super class: Circle Sub class: Cylinder “is-a” relation: Cylinder is-a Circle  Hint: Follow the style and ideology of Java program ProgGeometricObject.java

22 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 22 Task 2 F Write a Java program to illustrate the inheritance relation among classes Rectangle and Box/Pool Super class: Rectangle Sub class: Box “is-a” relation: Box is-a Rectangle  Hint: Follow the style and ideology of Java program ProgGeometricObject.java

23 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 23 Superclasses and Subclasses F Super class = parent class = base class F Sub class = child class = derived class F Given: class c1 is derived from class c2 F Class c1 is a sub class: – derived class, extended class, child class, F Class c2 is a super class: – base class, parent class

24 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 24 Superclasses and Subclasses F Sub class is not a sub set of the super class  private data fields in a super class are not accessible in sub class. They can be accessed/mutated through public getter/setter methods if defined F Inheritance models “is-a” relation. BUT Not all “is-a” relations should be modeled using inheritance. No need to define a Square class to extend Rectangle, because there is nothing to supplement from rectangle to square. For class A to extend class B, A should contain more detailed information than B. F Java allows only one super class, or single inheritance. No direct multiple inheritance, but achieved through interfaces.

25 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 25 Are superclass’s Constructor Inherited? No. They are not inherited. They can not be invoked by name. They are invoked implicitly or may be invoked 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 implicitly invoked.

26 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 26 Superclass’s Constructor Is Always Invoked A constructor may invoke an overloaded constructor or its superclass’s constructor. If none of them is invoked explicitly, the compiler puts super() as the first statement in the constructor. For example,

27 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 27 Superclass constructors The very first thing any subclass constructor does is call automatically the default constructor for its superclass –class Foo extends Bar { Foo() { // constructor super(); // invisible call to superclass constructor... You can replace this with a call to a specific superclass constructor –Use the keyword super –This must be the very first thing the constructor does –class Foo extends Bar { Foo(String name) { // constructor super(name, 5); // explicit call to superclass constructor...

28 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 28 Using the Keyword super F To call a superclass constructor – super(); – super(arguments); F To call a superclass method – super.method(arguments); Keyword this used to refer to the calling object. Keyword super refers to the superclass of the class in which super appears. This keyword can be used in two ways:

29 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 29 CAUTION You must use the keyword super to call the superclass constructor. ATTENTION: 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.

30 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 30 Example 3-arg constructor of Circle class: public Circle(double radius, String color, boolean filled) { setColor(color); setFilled(filled); this.radius = radius; } Can be replaced with: public Circle(double radius, String color, boolean filled) { super(color, filled); this.radius = radius; }

31 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 31 Constructor chaining F Given the class hierarchy: F Class Person – super class ↑ F Class Employee – sub class and super class ↑ F Class Faculty – sub sub class

32 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 32 Constructor 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"); } } // end of class Faculty 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); } } // end of class Employee class Person { public Person() { System.out.println("(1) Person's no-arg constructor is invoked"); } } // end of class Person Constructing an instance of a class invokes all the superclasses’ constructors along the inheritance chain. This is called constructor chaining.

33 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 33 Trace execution  Stmt new Faculty(); creates object, invokes no-arg constructor Faculty() F This means –Super() for Employee –Stmts of Faculty() constructor F This means –Super() for Person –Stmts for Employee() constructor –Stmts for Faculty() constructor F Trace execution on coming 9 slides or skip them

34 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 34 Trace Execution 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"); } 1. Start from the main method animation

35 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 35 Trace Execution 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"); } 2. Invoke Faculty constructor animation

36 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 36 Trace Execution 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"); } 3. Invoke Employee’s no- arg constructor animation

37 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 37 Trace Execution 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"); } 4. Invoke Employee(String) constructor animation

38 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 38 Trace Execution 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"); } 5. Invoke Person() constructor animation

39 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 39 Trace Execution 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"); } 6. Execute println animation

40 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 40 Trace Execution 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"); } 7. Execute println animation

41 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 41 Trace Execution 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"); } 8. Execute println animation

42 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 42 Trace Execution 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"); } 9. Execute println animation

43 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 43 Overriding Members F You can override (most) methods in a parent class by defining a method with the same name and parameter list in the child class. F This is useful for changing the behavior of a class without changing its interface.

44 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 44 Example of Overriding  Here we override to change method getIdentifier() public class Person { private String name; private String ssn; public void setName(String name) { this.name = name; } public String getName() { return name; } public String getIdentifier() { return ssn; } public class Student extends Person { private String studentId; private double accountBalance; public void increaseBalance(double amount) { this.accountBalance += amount; } public double getAccountBalance() { return accountBalance; } public String getIdentifier() { // override return studentId; // use student id instead of ssn }

45 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 45 Overriding Methods in the Superclass 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 GeometricObject { public String toString() {return "Created on:" + dateCreated + "\nColor:" + color + " filled:" + filled; } } // end of class Geometric Object //============================================================== 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; }

46 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 46 NOTE 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.

47 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 47 NOTE 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.

48 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 48 Overriding vs. Overloading

49 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 49 Overriding vs. Overloading F Overloading methods in base class and derived class F Base class and derived class have method with –Same name –Different type and/or number of parameters F Test Java Program TestOverLoad.java

50 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 50 Overriding vs. Overloading // file TestOverload.java class B { public void p(int par) { System.out.println(" Base class method " + par*2 ); } } class A extends B { public void p(double par) { // this method overloads base class method p() System.out.println(" Child class method " + par); } } public class TestOverLoad { public static void main(String[] args) { A a = new A(); a.p(10); a.p(10.0); } }

51 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 51 Overriding vs. Overloading F Overriding methods in base class and derived class F Base class and derived class have method with –Same name –Same type and/or number of parameters F Test Java Program TestOverRide.java

52 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 52 Overriding vs. Overloading // file TestOverRide.java class B { public void p(double par) { System.out.println(" Base class method " + par*2 ); } } class A extends B { public void p(double par) { // this method overrides base class method p() System.out.println(" Child class method " + par); //super.p(10); //super.p(10.0); } } public class TestOverRide { public static void main(String[] args) { A a = new A(); a.p(10); a.p(10.0); } }

53 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 53 The Object Class and Its Methods Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when a class is defined, the superclass of the class is Object.

54 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 54 The Object class  It is important to be familiar with methods provided by the Object class so that you can use them in your classes. F Some of these methods are: – public boolean equals(Object object) – public int hashCode() – public String toString()

55 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 55 The toString() method in Object The toString() method returns a string representation of the object. The default implementation returns a string consisting of a class name of which the object is an instance, the at sign (@), and a number representing this object. Circle circle = new Circle(); System.out.println(circle.toString()); The code displays something like Circle@15037e5. This message is not very helpful or informative. Usually you should override the toString method so that it returns a digestible string representation of the object.

56 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 56 The equals Method The equals() method compares the contents of two objects. The default implementation of the equals method in the Object class is as follows: public boolean equals(Object obj) { return (this == obj); } Using the equals method is equivalent to the == operator in the object class, BUT it is intended for the subclasses of the Object class to modify (override) the equals method to test whether two distinct objects have the same content

57 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 57 The hashCode Method  Invoking hashCode() on object returns the object’s hash code. F Hash code is an integer that can be used to store the object in a hash set so that it can be located quickly.  Method hashCode() returns the internal memory address of the object in hex  You should override hashCode() whenever you override equals() method. WHY? If two objects are equal, their hash codes must be the same.

58 Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 013213080758 Thank You for Your attention!


Download ppt "Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807 1 COS240 O-O Languages AUBG,"

Similar presentations


Ads by Google