Chapter 10 Thinking in Objects - Manal Helal

56
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 10 Thinking in Objects

Transcript of Chapter 10 Thinking in Objects - Manal Helal

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

Chapter 10 Thinking in Objects

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

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. 3

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. 4

Class Abstraction and EncapsulationClass 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 Contract (Signatures of

public methods and public constants)

Class

Class implementation is like a black box hidden from the clients

Clients use the

class through the contract of the class

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

Designing the Loan Class

TestLoanClass RunLoan

Loan

-annualInterestRate: double -numberOfYears: int -loanAmount: double -loanDate: Date +Loan() +Loan(annualInterestRate: double,

numberOfYears: int, loanAmount: double)

+getAnnualInterestRate(): double +getNumberOfYears(): int +getLoanAmount(): double +getLoanDate(): Date +setAnnualInterestRate( annualInterestRate: double): void +setNumberOfYears( numberOfYears: int): void +setLoanAmount( loanAmount: double): void +getMonthlyPayment(): double +getTotalPayment(): double

The annual interest rate of the loan (default: 2.5). The number of years for the loan (default: 1) The loan amount (default: 1000). The date this loan was created. Constructs a default Loan object. Constructs a loan with specified interest rate, years, and

loan amount. Returns the annual interest rate of this loan. Returns the number of the years of this loan. Returns the amount of this loan. Returns the date of the creation of this loan. Sets a new annual interest rate to this loan.

Sets a new number of years to this loan. Sets a new amount to this loan. Returns the monthly payment of this loan. Returns the total payment of this loan.

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

Object-Oriented ThinkingChapters 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. 7

The BMI Class

UseBMIClass RunBMI

BMI

-name: String -age: int -weight: double -height: double +BMI(name: String, age: int, weight:

double, height: double) +BMI(name: String, weight: double,

height: double) +getBMI(): double +getStatus(): String

The name of the person. The age of the person. The weight of the person in pounds. The height of the person in inches. Creates a BMI object with the specified

name, age, weight, and height. Creates a BMI object with the specified

name, weight, height, and a default age 20.

Returns the BMI Returns the BMI status (e.g., normal,

overweight, etc.)

The get methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

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

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. 9

Class RepresentationAn 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 { private Name name; private Address address; ... }

public class Address { ... }

Aggregated class Aggregating class Aggregated class

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

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. 11

Aggregation Between Same ClassAggregation may exist between objects of the same class. For example, a person may have a supervisor.

Person Supervisor

1

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. 12

Aggregation Between Same ClassWhat happens if a person has several supervisors?

Person Supervisor

1

m

p ublic c lass Pe rson { ... privat e Perso n[] su perviso rs; }

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

Example: The Course Class

TestCourse RunCourse

Course

-courseName: String -students: String[] -numberOfStudents: int

+Course(courseName: String) +getCourseName(): String +addStudent(student: String): void +dropStudent(student: String): void +getStudents(): String[] +getNumberOfStudents(): int

The name of the course. An array to store the students for the course. The number of s tudents (default : 0).

Creates a course with the specified name. Returns the course name.

Adds a new student to the course. Drops a student from the course. Returns the students in the course. Returns the number of students in the course.

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

Example: The StackOfIntegers Class

RunTestStackOfIntegers

StackOfIntegers

-elements: int[] -size: int

+StackOfIntegers() +StackOfIntegers(capacity: int) +empty(): boolean +peek(): int

+push(value: int): int +pop(): int +getSize(): int

An array to store integers in the stack.

The number of integers in the stack.

Constructs an empty stack with a default capacity of 16. Constructs an empty stack with a specified capacity. Returns true if the stack is empty. Returns the integer at the top of the stack without

removing it from the stack. Stores an integer into the top of the stack. Removes the integer at the top of the stack and returns it. Returns the number of elements in the stack.

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

Designing the StackOfIntegers Class

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

Implementing StackOfIntegers Class

StackOfIntegers

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

Wrapper Classes❑ Boolean

❑ Character ❑ Short ❑ Byte

❑ Integer ❑ Long ❑ Float ❑ Double

NOTE: (1) The wrapper classes do not have no-arg constructors. (2) The instances of all wrapper classes are immutable, i.e., their internal values cannot be changed once the objects are created.

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

The Integer and Double Classes

java.lang.Integer

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

java.lang.Double -value: double +MAX_VALUE: double +MIN_VALUE: double +Double(value: double) +Double(s: String) +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double +compareTo(o: Double): int +toString(): String +valueOf(s: String): Double +valueOf(s: String, radix: int): Double +parseDouble(s: String): double +parseDouble(s: String, radix: int): double

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

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. 2020

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. 2121

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. 2222

Conversion MethodsEach 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. 2323

The Static valueOf MethodsThe 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. 2424

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. 2525

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):

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

(a)

Equivalent

(b)

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

New JDK 1.5 boxing

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. 2626

BigInteger and BigDecimalIf 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. 2727

BigInteger and BigDecimalBigInteger a = new BigInteger("9223372036854775807"); BigInteger b = new BigInteger("2"); BigInteger c = a.multiply(b); // 9223372036854775807 * 2 System.out.println(c);

BigDecimal a = new BigDecimal(1.0); BigDecimal b = new BigDecimal(3); BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP); System.out.println(c);

LargeFactorial Run

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28

Chapter 11 Inheritance and Polymorphism

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 29

MotivationsSuppose 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) 2013 Pearson Education, Inc. All rights reserved. 30

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) 2013 Pearson Education, Inc. All rights reserved. 31

Superclasses and Subclasses

GeometricObject

TestCircleRectangle

Run

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

+GeometricObject() +GeometricObject(color: String,

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

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

Creates a GeometricObject. Creates a GeometricObject with the specified color and filled

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

Circle -radius: double

+Circle() +Circle(radius: double) +Circle(radius: double, color: String,

filled: boolean) +getRadius(): double +setRadius(radius: double): void +getArea(): double +getPerimeter(): double +getDiameter(): double +printCircle(): void

Rectangle -width: double -height: double

+Rectangle() +Rectangle(width: double, height: double) +Rectangle(width: double, height: double

color: String, filled: boolean) +getWidth(): double +setWidth(width: double): void +getHeight(): double +setHeight(height: double): void +getArea(): double +getPerimeter(): double

CircleFromSimpleGeometricObject

RectangleFromSimpleGeometricObject

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32

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) 2013 Pearson Education, Inc. All rights reserved. 33

Superclass’s Constructor Is Always InvokedA 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(double d) { // some statements }

is equivalent to

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

public A() { }

is equivalent to

public A() { super(); }

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

Using the Keyword super

To call a superclass constructor To call a superclass method

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

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35

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) 2013 Pearson Education, Inc. All rights reserved. 36

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() { System.out.println("(1) Person's no-arg constructor is invoked"); } }

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

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 37

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

1. Start from the main method

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 38

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

2. Invoke Faculty constructor

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39

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

3. Invoke Employee’s no-arg constructor

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40

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

4. Invoke Employee(String) constructor

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 41

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

5. Invoke Person() constructor

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 42

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

6. Execute println

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 43

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

7. Execute println

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 44

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

8. Execute println

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 45

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

9. Execute println

animation

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 46

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

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

Find out the errors in the program:

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 47

Defining a SubclassA subclass inherits from a superclass. You can also: Add new properties Add new methods

Override the methods of the superclass

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 48

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

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

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 49

Overriding Methods in the SuperclassA 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. 50

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. 51

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. 52

Overriding vs. Overloading public class Test { publ ic stat ic void main( String[ ] args) { A a = new A(); a. p(10); a. p(10.0) ; } } class B { publ ic void p(doub le i) { Sy stem.ou t.print ln(i * 2); } } class A exten ds B { // T his met hod ove rrides the me thod in B publ ic void p(doub le i) { Sy stem.ou t.print ln(i); } }

public class T est { publi c stati c void main(St ring[] args) { A a = new A(); a.p (10); a.p (10.0); } } class B { publi c void p(doubl e i) { Sys tem.out .printl n(i * 2 ); } } class A extend s B { // Th is meth od over loads t he meth od in B publi c void p(int i ) { Sys tem.out .printl n(i); } }

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

public class Circle { ... }

Equivalent public class Circle extends Object { ... }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 54

The toString() method in ObjectThe 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) 2015 Pearson Education, Inc. All rights reserved. 55

• 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.

Assignment – ass7

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

• 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 initialise all attributes with sample data of your choice and print their contents.

BONUS ASSIGNMENT