You are on page 1of 56

Chapter 10 Thinking in Objects

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 1
Motivations

You see the advantages of object-oriented programming


from the preceding chapter. This chapter will demonstrate
how to solve problems using the object-oriented paradigm.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 2
Objectives
❑ To apply class abstraction to develop software (§10.2).
❑ To explore the differences between the procedural paradigm and object-
oriented paradigm (§10.3).
❑ To discover the relationships between classes (§10.4).
❑ To design programs using the object-oriented paradigm (§§10.5–10.6).
❑ To create objects for primitive values using the wrapper classes (Byte,
Short, Integer, Long, Float, Double, Character, and Boolean)
❑ (§10.7).
To simplify programming using automatic conversion between primitive
❑ types and wrapper class types (§10.8).
To use the BigInteger and BigDecimal classes for computing very large
numbers with arbitrary precisions (§10.9).

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 3
Class Abstraction and
Encapsulation
Class abstraction means to separate class implementation
from the use of the class. The creator of the class provides
a description of the class and let the user know how the
class can be used. The user of the class does not need to
know how the class is implemented. The detail of
implementation is encapsulated and hidden from the user.

Class implementation Class Contract


is like a black box (Signatures of
hidden from the clients
Clients use the
Class public methods and class through the
public constants) contract of the class

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 4
Designing the Loan Class
Loan
-annualInterestRate: double The annual interest rate of the loan (default: 2.5).
-numberOfYears: int The number of years for the loan (default: 1)
-loanAmount: double The loan amount (default: 1000).
-loanDate: Date
The date this loan was created.
+Loan()
Constructs a default Loan object.
+Loan(annualInterestRate: double,
numberOfYears: int, Constructs a loan with specified interest rate, years, and
loanAmount: double) loan amount.
+getAnnualInterestRate(): double
+getNumberOfYears(): int Returns the annual interest rate of this loan.
+getLoanAmount(): double Returns the number of the years of this loan.
+getLoanDate(): Date Returns the amount of this loan.
+setAnnualInterestRate( annualInte Returns the date of the creation of this loan.
restRate: double): void Sets a new annual interest rate to this loan.
+setNumberOfYears( numbe
rOfYears: int): void Sets a new number of years to this loan.
+setLoanAmount( loanAmou
nt: double): void
Sets a new amount to this loan.
+getMonthlyPayment():
double Returns the monthly payment of this loan.
+getTotalPayment(): double Returns the total payment of this loan.

Loan TestLoanClass Run


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 5
Object-Oriented Thinking
Chapters 1-8 introduced fundamental programming
techniques for problem solving using loops, methods, and
arrays. The studies of these techniques lay a solid
foundation for object-oriented programming. Classes
provide more flexibility and modularity for building
reusable software. This section improves the solution for a
problem introduced in Chapter 3 using the object-oriented
approach. From the improvements, you will gain the
insight on the differences between the procedural
programming and object-oriented programming and see the
benefits of developing reusable code using objects and
classes.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 6
The BMI Class
The get methods for these data fields are
provided in the class, but omitted in the
UML diagram for brevity.
BMI
-name: String The name of the person.
-age: int The age of the person.
-weight: double The weight of the person in pounds.
-height: double The height of the person in inches.

+BMI(name: String, age: int, weight: Creates a BMI object with the specified
double, height: double) name, age, weight, and height.
+BMI(name: String, weight: double, Creates a BMI object with the specified
height: double) name, weight, height, and a default age
20.
+getBMI(): double Returns the BMI
+getStatus(): String Returns the BMI status (e.g., normal,
overweight, etc.)

BMI UseBMIClass Run


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 7
Object Composition
Composition is actually a special case of the aggregation
relationship. Aggregation models has-a relationships and
represents an ownership relationship between two objects.
The owner object is called an aggregating object and its
class an aggregating class. The subject object is called an
aggregated object and its class an aggregated class.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 8
Class Representation
An aggregation relationship is usually represented as a data
field in the aggregating class. For example, the
relationship in Figure 10.6 can be represented as follows:

public class Name { public class Student public class Address {


... { private Name name; ...
} private Address }
address;

...
}
Aggregated class Aggregating Aggregated
class class

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 9
Aggregation or Composition
Since aggregation and composition
relationships are represented using classes in
similar ways, many texts don’t differentiate
them and call both compositions.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 10
Aggregation Between Same Class
Aggregation may exist between objects of the same
class. For example, a person may have a supervisor.

1
Person
Supervisor
1

public class Person {


// The type for the data is the class itself
private Person supervisor;
...
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 11
Aggregation Between Same Class
What happens if a person has several supervisors?

1
Person
Supervisor
m

p u b l i c c l a s s P e r s o n
{
. . .
p r i v a t e P e r s o n [ ] s
u p e r v i s o r s ;
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 12
Example: The Course Class
Course
-courseName: String The name of th e course.
-students: String[] An array to store the students for the course.
-numberOfStudents: int The number of s tudent s (default : 0).
+Course(courseName: String) Creates a course with the specifi ed
+getCourseName(): String name. Returns the course name.
+addStudent(student: String): void Ad ds a new student to the course.
+dropStudent(student: String): void Drops a student from the course.
+getStudents(): String[]
Returns the student s in the
+getNumberOfStudents(): int
course.
Returns the number of students in
the course.

Course TestCourse Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 13
Example: The StackOfIntegers
Class
StackOfIntegers
-elements: int[] An array to store integers in the stack.
-size: int The number of integers in the stack.
+StackOfIntegers() Constructs an empty stack with a default capacity of 16.
+StackOfIntegers(capacity: int) Constructs an empty stack with a specified capacity.
+empty(): boolean Returns true if the stack is empty.
+peek(): int Returns the integer at the top of the stack without
removing it from the stack.
+push(value: int): int
Stores an integer into the top of the stack.
+pop(): int
+getSize(): int
Removes the integer at the top of the stack and returns it.
Returns the number of elements in the stack.

TestStackOfIntegers Run
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 14
Designing the StackOfIntegers Class

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 15
Implementing StackOfIntegers
Class

StackOfIntegers

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 16
Wrapper Classes
❑ Boolean ❑ Integer NOTE: (1) The wrapper classes do
not have no-arg constructors. (2)
❑ Character ❑ Long The instances of all wrapper classes
are immutable, i.e., their internal
❑ Short ❑ Float values cannot be changed once the
objects are created.
❑ Byte ❑ Double

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 17
The Integer and Double
Classes
java.lang.Integer java.lang.Double
-value: int -value: double
+MAX_VALUE: int +MAX_VALUE: double
+MIN_VALUE: int +MIN_VALUE: double

+Integer(value: int) +Double(value: double)


+Integer(s: String) +Double(s: String)
+byteValue(): byte +byteValue(): byte
+shortValue(): short +shortValue(): short
+intValue(): int +intValue(): int
+longVlaue(): long +longVlaue(): long
+floatValue(): float +floatValue(): float
+doubleValue():double +doubleValue():double
+compareTo(o: Integer): int +compareTo(o: Double): int
+toString(): String +toString(): String
+valueOf(s: String): Integer +valueOf(s: String): Double
+valueOf(s: String, radix: int): Integer +valueOf(s: String, radix: int): Double
+parseInt(s: String): int +parseDouble(s: String): double
+parseInt(s: String, radix: int): int +parseDouble(s: String, radix: int): double

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 18
The Integer Class
and the Double
Class
❑ Constructors

❑Class Constants MAX_VALUE, MIN_VALUE

❑Conversion Methods

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 19
Numeric Wrapper Class Constructors
You can construct a wrapper object either from a
primitive data type value or from a string
representing the numeric value. The constructors
for Integer and Double are:
public Integer(int value)
public Integer(String s)
public Double(double value)
public Double(String s)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 20
Numeric Wrapper Class Constants
Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE. MAX_VALUE
represents the maximum value of the corresponding
primitive data type. For Byte, Short, Integer, and Long,
MIN_VALUE represents the minimum byte, short, int,
and long values. For Float and Double, MIN_VALUE
represents the minimum positive float and double values.
The following statements display the maximum integer
(2,147,483,647), the minimum positive float (1.4E-45),
and the maximum double floating-point number
(1.79769313486231570e+308d).

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 21
Conversion Methods
Each numeric wrapper class implements the
abstract methods doubleValue, floatValue,
intValue, longValue, and shortValue, which
are defined in the Number class. These
methods “convert” objects into primitive type
values.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 22
The Static valueOf Methods
The numeric wrapper classes have a useful
class method, valueOf(String s). This method
creates a new object initialised to the value
represented by the specified string. For
example:

Double doubleObject = Double.valueOf("12.4");


Integer integerObject = Integer.valueOf("12");

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 23
The Methods for Parsing Strings into Numbers

You have used the parseInt method in the


Integer class to parse a numeric string into an
int value and the parseDouble method in the
Double class to parse a numeric string into a
double value. Each numeric wrapper class has
two overloaded parsing methods to parse a
numeric string into an appropriate numeric
value.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 24
Automatic Conversion Between Primitive Types
and Wrapper Class Types

JDK 1.5 allows primitive type and wrapper classes to be converted automatically. For
example, the following statement in (a) can be simplified as in (b):

Equivalent
Integer[] intArray = {new Integer(2), Integer[] intArray = {2, 4, 3};
new Integer(4), new Integer(3)};

(a) New JDK 1.5 boxing (b)

Integer[] intArray = {1, 2, 3};


System.out.println(intArray[0] + intArray[1] + intArray[2]);

Unboxing

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 25
BigInteger and BigDecimal
If you need to compute with very large integers or
high precision floating-point values, you can use
the BigInteger and BigDecimal classes in the
java.math package. Both are immutable. Both
extend the Number class and implement the
Comparable interface.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 26
BigInteger and BigDecimal
BigInteger a = new BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 * 2
System.out.println(c);

LargeFactorial Run

BigDecimal a = new BigDecimal(1.0);


BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 27
Chapter 11 Inheritance and Polymorphism

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 28
Motivations
Suppose you will define classes to model circles,
rectangles, and triangles. 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, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 29
Objectives





























































































To define a subclass from a superclass through inheritance



















 (§11.2).


















































































































 To invoke the superclass’s constructors and methods using





















 the super keyword
 (§11.3).





























































































To override instance methods in the subclass (§11.4).






































































































































 To distinguish differences between overriding and overloading





















 (§11.5).
 To explore the toString() method in the Object class (§11.6).





























































































To



















 discover polymorphism and dynamic binding (§§11.7–11.8).


















































































































 To





















 describe casting and explain why explicit downcasting is necessary (§11.9).
 To explore the equals method in the Object class (§11.10).





























































































To store, retrieve, and manipulate objects in an ArrayList (§11.11).






































































































































 To implement a Stack class using ArrayList (§11.12).






















 To enable data and methods in a superclass accessible from subclasses using





























































































the






































































































































protected visibility modifier (§11.13).


























































































































































































































































 To prevent class extending and method overriding using the final modifier








































































































































 (§11.14).




































































































































































































































































































































































































 Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
30
rights reserved.

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, Creates a GeometricObject with the specified color and filled
filled: boolean) values.
+getColor(): String Returns the color.
+setColor(color: String): void Sets a new color. GeometricObject
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void
Sets a new filled property.
+getDateCreated(): java.util.Date
+toString(): String
Returns the dateCreated. CircleFromSimpleGeometricObject
Returns a string representation of this object.

RectangleFromSimpleGeometricObject
Circle Rectangle
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
+setRadius(radius: double): void +getWidth(): double
TestCircleRectangle
+getArea(): double +setWidth(width: double): void
+getPerimeter(): double +getHeight(): double
+getDiameter(): double
+printCircle(): void
+setHeight(height: double): void
+getArea(): double Run
+getPerimeter(): double

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 31
Are superclass’s Constructor 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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 32
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,

public A() { public A()


is equivalent to
} { super()
;
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 33
Using the Keyword super
The keyword super refers to the
superclass of the class in which super
appears. This keyword can be used in two
ways:





Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 34
CAUTION

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.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 35
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’ constructors along
the inheritance chain. This is known as 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");
}
}

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() { Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 36
System.out.printl
animation
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) { 1. Start from the
new Faculty();
} 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.printl
n("(1) Person's
no-arg
constructor Liang,
is Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 37
invoked");
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[] 2. Invoke Faculty
new {
args) 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.printl
n("(1) Person's
no-arg
constructor Liang,
is Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 38
invoked");
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[]
new {
args) Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
} 3. Invoke Employee’s no-
arg 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.printl
n("(1) Person's
no-arg
constructor Liang,
is Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All 39
rights reserved.
invoked");
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[]
new {
args) Faculty();
}

public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
4. Invoke Employee(String)
class Employee extends Person { constructor
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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 40
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[]
new {
args) 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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 41
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[]
new {
args) 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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 42
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[]
new {
args) 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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 43
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[]
new {
args) 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.printl
n("(1) Person's
no-arg
constructor Liang,
is Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All 44
rights reserved.
invoked");
animation
Trace Execution
public class Faculty extends Employee
{ public static void main(String[]
new {
args) 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.printl
n("(1) Person's
no-arg
constructor Liang,
is Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All 45
rights reserved.
invoked");
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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 46
Defining a Subclass
A subclass inherits from a superclass. You can also:






Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 47
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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 48
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 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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 49
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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 50
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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 51
Overriding vs. Overloading
p u b l i c c l a s s T e s t { p u b l i c c l a s s T e s t {
p u b l i c s t a t i c v o i d a r g s p u b l i c s t a t i c v o i d a r g
m a i n ( S t r i n g [ ] A a ) { m a i n ( S t r i n g [ ] A a s ) {
= n e w A ( ) ; = n e w A ( ) ;
a . p ( 1 0 ) ; a . p ( 1 0 ) ;
a . p ( 1 0 . 0 ) ; a . p ( 1 0 . 0 ) ;
} }
} }
c l a s s B {
c l a s s B { p u b l i c v o i d p ( d o u b l e i )
p u b l i c v o i d p ( d o u b l {
e i ) { S y s t e m . o u t . p r i n t l n
S y s t e m . o u t . p r i n t ( i * 2 ) ;
l n ( i * 2 ) ; }
} }
}
c l a s s A e x t e n d s B {
c l a s s A e x t e n d s B { / / T h i s m e t h o d o v e r l o a d
/ / T h i s m e t h o d o v e r r s t h e m e t h o d i n B
i d e s t h e m e t h o d i n B p u b l i c v o i d p ( i n t i ) {
p u b l i c v o i d p ( d o u b l S y s t e m . o u t . p r i n t l n
e i ) { ( i ) ;
S y s t e m . o u t . p r i n t }
l n ( i ) ; }
}
}

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 52
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 { public class Circle extends Object {


... Equivalent
...
} }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 53
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.

Loan loan = new Loan();


System.out.println(loan.toString());

The code displays something like Loan@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, Tenth Edition, (c) 2013 Pearson Education, Inc. All
rights reserved. 54
Assignment – ass7
• 11.3 (Subclasses of Account) In Exercise 8.7,
the Account class was defined to model a bank
account. An account has the properties
account number, balance, annual interest rate,
and date created, and methods to deposit and
withdraw funds. Create two subclasses for
checking and saving accounts. A checking
account has an over- draft limit, but a savings
account cannot be overdrawn.
• Draw the UML diagram for the classes.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All
rights reserved. 55
BONUS

ASSIGNMENT
Complete the implementation of the Person, Employee, Faculty classes in slides
10:19, such that:
– All classes has no-arg constructors, and overloaded constructors to initialise the attributes
of all inherited levels.
– All classes have setters and getters methods for all their attributes.
– All classes have toString method and equals methods overridden.
– The Person class has the following attributes:





























































































































































































































































 A public String data field named FirstName

A public String data field named LastName






























































































































































































































































– The
 Employee class has the following attributes:






























































































































































































































































 A private double data field named Salary

A private int data field named JobGrade that defines the grade of the employee, for



























































































































































































































































 example Admin has grade 3, Lecturer has grade 2, TA has grade 1.


– The Faculty class has the following attributes:































































































































































































































































 A public String Array data field named SpecialisationAreas

A public int Array of named specPubCount for publications count in each specialisation



























































































































































































































































 area.


– Develop a test program to define 3 admin employees, and 2 faculty staff objects, and
initalisLeai nagl,lInatrtotdruicbtiuontetosJawvaitPhrogsraammmpni lge, TdenathtaEdotifony,
56
(oc)u2r01c5hPoeiacrseonaEndducaptironn i ,Itnct.hrights reserved.
Ael ir contents.

You might also like