Download COS240Lec13_JAVAInheritance

Document related concepts
no text concepts found
Transcript
COS240 O-O Languages
AUBG, COS dept
Lecture 13
Title:
Inheritance in Java
Reference: COS240 Syllabus
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
1
Lecture Contents:
To develop a subclass from a superclass through
inheritance
 To invoke the superclass’s constructors and
methods using super keyword.
 To override instance methods in the subclass.
 To distinguish differences between overriding
and overloading.
 To explore the toString(), equals()
methods in the Object class.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
2
Motivations
Suppose
you will define classes to model:
– students,
– instructors,
– professors.
You can build a separate independent class for each one
of the listed categories.

BUT: These classes have many common features.
What
is the best way to design these classes so to avoid
redundancy? The answer is to use inheritance.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
Motivations
Suppose
you will define classes to model
– circles,
– rectangles,
– triangles.
You
can build a separate independent class for each one
of the listed categories (2D geometric figures).
BUT: These classes have many common features.
What is the best way to design these classes so to avoid
redundancy? The answer is to use inheritance.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
4
Motivations
Suppose
you will define classes to model
– circles,
– cylinders.
You
can build a separate independent class for each one
of the listed categories.
BUT: These classes have many common features.
What
is the best way to design these classes so to avoid
redundancy? The answer is to use inheritance.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
5
Motivations
Suppose
you will define classes to model
– rectangles,
– boxes.
You can build a separate independent class for each one
of the listed categories.

BUT: These classes have many common features.
What is the best way to design these classes so to avoid
redundancy? The answer is to use inheritance.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
6
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.
7
Brief presentation
8
Inheritance
• A class can inherit properties and
methods from another class, called its
parent.
• In Java, this is called extending a class.
• The class doing the extending is the
child- or sub-class.
• The class getting extended is the parent
or super-class.
9
Inheritance
• In Java, a class can only extend one
parent.
– No multiple inheritance like in C++.
• You can also:
Add
new properties/attributes/data
fields
Add
new methods
Override
class
the methods of the super10
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 trees are drawn
upside-down, with the root at the top!
• Every class except Object has one
“parent” class, or super-class  single
inheritance.
• Each class is subclass of its super-class
.
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
Inheritance Example
Parent
public class Person {
protected String name;
Child
public class Student extends Person {
private double accountBalance;
public void setName(String name) {
this.name = name;
}
}
public String getName() {
return name;
}
Here is the
extends keyword,
signaling inheritance
public void increaseBalance(double amount) {
this.accountBalance += amount;
}
}
public double getAccountBalance() {
return accountBalance;
}
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
Superclass
Subclass
public class Person{
protected String name;
public class Student extends
Person {
private int studentNumber;
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;
}
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
Comprehensive presentation
16
Superclasses and Subclasses
Class is used to model objects of same type.
 Different classes may have common
properties/behaviors which can be generalized in a
class that can be shared by other classes.
 Inheritance enables you to define a general class
and later extend it to more specific classes.
 Consider geometric objects such as circles and
rectangles – next slide

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
17
Superclasses and Subclasses
 Geometric
objects: circles and rectangles
 Common properties:
– Color, filled/nofilled, dateCreated
 Circle
– specific properties:
– radius
 Rectangle
– specific properties:
– width, height
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
18
Superclasses and Subclasses
GeometricObject
-color: String
The color of the object (default: white).
-filled: boolean
Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date
The date when the object was created.
+GeometricObject()
Creates a GeometricObject.
+GeometricObject(color: String,
filled: boolean)
Creates a GeometricObject with the specified color and filled
values.
+getColor(): String
Returns the color.
+setColor(color: String): void
Sets a new color.
+isFilled(): boolean
Returns the filled property.
+setFilled(filled: boolean): void
Sets a new filled property.
+getDateCreated(): java.util.Date
Returns the dateCreated.
+toString(): String
Returns a string representation of this object.
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+Circle(radius: double, color: String,
filled: boolean)
+Rectangle(width: double, height: double)
+getRadius(): double
+Rectangle(width: double, height: double
color: String, filled: boolean)
+setRadius(radius: double): void
+getWidth(): double
+getArea(): double
+setWidth(width: double): void
+getPerimeter(): double
+getHeight(): double
+getDiameter(): double
+setHeight(height: double): void
+printCircle(): void
+getArea(): double
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
+getPerimeter(): double
rights reserved. 0132130807
19
Superclasses and Subclasses

Inheritance illustrated as skeletal Java source
class GeometricObject {
…
}
class Circle extends GeometricObject {
…
}
class Rectangle extends GeometricObject {
…
}
public class TestProgram {
public static void main(…) {
…
}
…
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
}
rights reserved. 0132130807
20
class GeometricObject
 Inheritance
illustrated as skeletal Java source
See detailed source text
in file
ProgGeometricObject.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
21
Task 1
 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 of Java program
ProgGeometricObject.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
22
Task 2
 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 of Java program
ProgGeometricObject.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
23
Superclasses and Subclasses
Super class = parent class = base class
 Sub class
= child class = derived class




Given: class c1 is derived from class c2
Class c1 is a sub class:
– derived class, extended class, child class,
Class c2 is a super class:
– base class, parent class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
24
Superclasses and Subclasses
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
 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.
 Java allows only one super class, or single inheritance.
No direct multiple inheritance, but achieved through
interfaces.

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, 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.
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 (using
this) or its superclass’s constructor (using super). If none of
them is invoked explicitly, the compiler puts super() as the
first statement in the constructor. For example,
public A() {
}
public A(double d) {
// some statements
}
public A() {
super();
}
is equivalent to
is equivalent to
public A(double d) {
super();
// some statements
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
27
Superclass’s Constructor Is Always Invoked
Next slide explanation
of
high importance.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
28
Superclass’s Constructor Is Always Invoked
In any case, constructing an instance of a class invokes the
constructors of all the superclasses along the inheritance
chain.
When constructing an object of a subclass, the subclass
constructor first invokes its superclass constructor before
performing its own tasks.
If the superclass is derived from another class, the
superclass constructor invokes its parent-class constructor
before performing its own tasks
This process continues until the last constructor along the
inheritance hierarchy is called.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
29
Superclass’s Constructor Is Always Invoked
The process described on the previous slide is known as
constructor chaining.
Demo programs:
faculty.java
and
SonFatherGrandFather.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
30
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
31
...
rights reserved. 0132130807
Using the Keyword super
• 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:


To call a superclass constructor
–
super();
–
super(arguments);
To call a superclass method
–
super.method(arguments);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
32
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
33
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;
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
34
Constructor chaining
 Given
the class hierarchy:
Person – super class
↑
 Class Employee – sub class and super class
↑
 Class Faculty – sub sub class
 Class
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
35
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors
along the inheritance chain. This is called 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
Liang, Person
Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
36
Trace execution
Stmt new Faculty(); creates object,
invokes no-arg constructor Faculty()
 This means

– Super() for Employee
– Stmts of Faculty() constructor

This means
– Super() for Person
– Stmts for Employee() constructor
– Stmts for Faculty() constructor

Trace execution on coming 9 slides or skip them
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
37
Trace execution
Main() -> Faculty() -> Employee() -> Employee(arg) -> Person()
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
38
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
1. Start from the
main method
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
39
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
2. Invoke Faculty
constructor
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
40
animation
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");
}
3. Invoke Employee’s noarg constructor
}
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
41
animation
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");
}
}
4. Invoke Employee(String)
constructor
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
42
animation
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);
}
}
5. Invoke Person() constructor
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
43
animation
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);
}
}
6. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
44
animation
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);
}
}
7. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
45
animation
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);
}
}
8. Execute println
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
46
animation
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");
}
}
9. Execute println
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");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
47
Example on the Impact of a Superclass
without no-arg Constructor
Find out the errors in the program:
public class Apple extends Fruit {
}
class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
48
Calling Superclass Methods
You 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);
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
49
Overriding Members
 You
can override (most) methods in
a parent class by defining a method
with the same name and the same
parameter list in the child class.
 This
is useful for changing the
behavior of a class without changing
its interface.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
50
Example of Overriding

Here we override to change method getIdentifier()
public class Person {
private String name;
private String ssn;
}
public class Student extends Person {
private String studentId;
private double accountBalance;
public void setName(String name) {
this.name = name;
}
public void increaseBalance(double amount) {
this.accountBalance += amount;
}
public String getName() {
return name;
}
public double getAccountBalance() {
return accountBalance;
}
public String getIdentifier() {
return ssn;
}
public String getIdentifier() { // override
return studentId; // use student id instead of ssn
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
51
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;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
52
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
53
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
54
Overriding vs. Overloading
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.p(10);
a.p(10.0);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class B {
public void p(double i) {
System.out.println(i * 2);
}
}
class A extends B {
// This method overrides the method in B
public void p(double i) {
System.out.println(i);
}
}
class A extends B {
// This method overloads the method in B
public void p(int i) {
System.out.println(i);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
55
Overriding vs. Overloading
 Overloading
methods in base class and
derived class
 Base class and derived class have method
with
– Same name
– Different type and/or number of parameters
 Test
Java Program TestOverLoad.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
56
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);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
57
Overriding vs. Overloading
 Overriding
methods in base class and
derived class
 Base class and derived class have method
with
– Same name
– Same type and/or number of parameters
 Test
Java Program TestOverRide.java
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
58
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);
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
}
rights reserved. 0132130807
59
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.
public class Circle {
...
}
Equivalent
public class Circle extends Object {
...
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
60
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.
 Some of these methods are:
– public boolean equals(Object object)
– public int hashCode()
– public String toString()
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
61
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
62
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
63
The hashCode Method
Invoking hashCode() on object returns the
object’s hash code.
 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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
64
Thank You
for
Your attention!
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807
65