copyright © 2014 by john wiley & sons. all rights reserved.1 inheritance

91
Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Inheritance

Upload: brenda-fletcher

Post on 18-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 1

Inheritance

Page 2: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 2

Goals

To learn about inheritance To implement subclasses that inherit and override

superclass methods To understand the concept of polymorphism To be familiar with the common superclass Object and

its methods

Page 3: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 3

Inheritance Hierarchies Inheritance:

• the relationship between a more general class (superclass) and a more specialized class (subclass).

• The subclass inherits data and behavior from the superclass.

• Cars share the common traits of all vehicles• Example: the ability to transport people from one place to

another

Figure 1 An Inheritance Hierarchy of Vehicle Classes

Vehicle

Motorcycle Car Truck

Sedan SUV

Page 4: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 4

Inheritance Hierarchies The class Car inherits from the class Vehicle The Vehicle class is the superclass The Car class is the subclass

Figure 2 Inheritance Diagram

Superclass

Subclass

Page 5: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 5

Inheritance Hierarchies Inheritance lets you can reuse code instead of duplicating it.

A class can be defined as a "subclass" of another class.

• The subclass inherits all data attributes of its superclass

• The subclass inherits all methods of its superclass

The subclass can:

Add new functionality

Use inherited functionality

Override inherited functionality (modify)

Employee-name-Id+getSalary()+getName()

SalariedEmployee-weeklySalary

+calculateBonus()

CommissionEmployee-grossSales-commissionRate+getCommissionRate()

Page 6: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 6

Employee

-name-Id+getSalary()

+getName()

+setID(id)

SalariedEmployee

-weeklySalary

+calculateBonus()

CommissionEmployee

-grossSales-commissionRate+getCommissionRate()

parent/supercalss of SalariedEmployee class and CommissionEmployee

Additional attributes

Additional methods

Inherited + overridden by subclasses

Inherited and used as it is by subclasses

Inherited and used as it is by subclasses

Page 7: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 7

What does a subclass inherit?

A subclass inherits :• Non-private Superclass variables• Non-private Superclass methods

A subclass does NOT inherit:• Superclass constructors• Superclass private variables• Superclass private methods.

Inherited variables and methods behave as though they were declared in the subclass.

The subclass may define additional variables and methods that were not present in the superclass.

Page 8: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 8

Inheritance in java

In Java, inheritanc is accomplished by extending an existing class (using keyword extends).

A superclass can be any previously existing class, including a class in the Java API.

E.g.:public class SalariedEmployee extends Employee{ …}

Subclass of Vehicle Superclass of Car

Page 9: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 9

Writing a Subclass Example

Public class Employee{

private String name;private int id;

public Employee(String name, int id){this.name=name; this.id=id;}public double getSalary(){return 2000.0;}public String getName(){ return name;}public void setId(int id){ this.id = id;}

}

Public class SalariedEmployee extends Employee{

private double weeklySalary;

public double getSalary(){return this.weeklySalary*4;}public double calculateBonus(){return this.weeklySalary*0.5; }

}

Employee.java

SalariedEmployee.javaSubclass:

Superclass:

Page 10: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 10

Question

Which of the following code lines gives compilation errors?

Public class SalariedEmployee extends Employee{

private double weeklySalary;

public double calculateBonus(){System.out.println(“calculationg bonus of employee

with

name:”+getName()+” id:”+id);

return this.weeklySalary*0.5;

}}

Page 11: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 11

Answer

Print statement will result in compiler error as it is private in Employee class.

Public class SalariedEmployee extends Employee{

private double weeklySalary;

public double calculateBonus(){System.out.println(“calculationg bonus of

employee with

name:”+getName()+” id:”+id);

return this.weeklySalary*0.5;

}}

Page 12: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 12

Question

Which of these statements will result in compiler error?

public class EmployeeDemo{ public static void main(String args[]) { SalariedEmployee salEmp = new SalariedEmployee();

salEmp.calculateBonus();

salEmp.setID(12345);

salEmp.getCommissionRate();

System.out.print(salEmp.id);

System.out.print(salEmp.weeklySalary);

}}

Employee-name-Id+getSalary()+getName()+setID(id)

SalariedEmployee-weeklySalary

+calculateBonus()

CommissionEmployee-grossSales-commissionRate+getCommissionRate()

Page 13: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 13

Answer

Which of these statements will result in compiler error?

public class EmployeeDemo{ public static void main(String args[]) { SalariedEmployee salEmp = new SalariedEmployee();

salEmp.calculateBonus();

salEmp.setID(12345);

salEmp.getCommissionRate();

System.out.print(salEmp.ID);

System.out.print(salEmp.weeklySalary);

}}

Employee-name-Id+getSalary()+getName()+setID(id)

SalariedEmployee-weeklySalary

+calculateBonus()

CommissionEmployee-grossSales-commissionRate+getCommissionRate()

Page 14: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 14

The substitution principle: • You can always use a subclass object when a superclass

object is expected.

Person

Employee

SalariedEmployee CommissionEmployee

Employee emp = new SalariedEmployee();

Person person = new SalariedEmployee();

Page 15: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 15

Question

Consider classes Manager and Employee. Which should be the superclass and which should be the subclass?

Page 16: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 16

Answer

Because every manager is an employee but not the other way around, the Manager class is more specialized. It is the subclass, and Employee is the superclass.

Page 17: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 17

Question

What are the inheritance relationships between classes BankAccount, CheckingAccount, and SavingsAccount?

Page 18: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 18

Answer

CheckingAccount and SavingsAccount both inherit from the more general class BankAccount.

Page 19: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 19

Question

Consider the method doSomething(Car c). List all vehicle classes from Figure 1 whose objects cannot be passed to this method.

Vehicle

Motorcycle Car Truck

Sedan SUV

Page 20: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 20

Answer

Answer: Vehicle, Truck, Motorcycle

doSomething(Car c) Vehicle

Motorcycle Car Truck

Sedan SUV

Page 21: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 21

Writing Subclass Constructors

A subclass (E.g. Salaried employee) DOES NOT inherit constructors from its superclass

So it will need its own constructors.

Two things are done in subclass constructor:1. Initialize variables of superclass (likely to be

private)• E.g. name, id in Employee class

2. Initialize variables declared in subclass• E.g. weeklySalary in SalariedEmployee class

Page 22: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 22

Writing Subclass Constructors

A first attempt at writing the constructor:

Is above an OK way to write subclass constructor?

public class SalariedEmployee extends Employee{

double weeklySalary;

public SalariedEmployee(String empName, int empId, double empWeekSal)

{name = empName;id = empId;weeklySalary = empWeekSal;

}}

Page 23: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 23

No. You will get compile time errors because name and id are declared private in employee class.

public class SalariedEmployee extends Employee{

double weeklySalary;

public SalariedEmployee(String empName, int empId, double empWeekSal )

{name = empName;

id = empId;

weeklySalary = empWeekSal; }

}

Page 24: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 24

Writing Subclass Constructors

Solution: super keyword

• Call superclass constructor within subclass constructor

• E.g. SalariedEmployee constructor:

public class SalariedEmployee extends Employee{double weeklySalary;public SalariedEmployee(String empName, int empId, double

empWeekSal){super(empName, empId);weeklySalary = empWeekSal;

} }

Super Must be the first statement in the subclass constructor

Page 25: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 2525

Writing Subclass Constructors

What if subclass constructor fails to call super?

• Then the compiler will automatically insert super() at the beginning of the constructor.

public SalariedEmployee(String empName, int empId, double empWeekSal)

{weeklySalary = empWeekSal;

}

Page 26: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 26

What if a subclass has no constructors at all?

• Then the compiler will create a no argument constructor in subclass that contains super().

• This will be the only statement in constructor.

Page 27: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 27

Programming Question

Write a class SavingsAccount that extends the BankAccount class. In addition to the public methods and variables declared in BankAccount class, SavingsAccount class need to define following:• Instance variable: interestRate

• Constructor that initializes interestRate and all variables in BankAccount class.

• Instance method: setInterestRate that set interest rate to parameter value

• Use BankAccount class code is in next slide

Page 28: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 28

public class BankAccount{ private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double initialBalance) { balance = initialBalance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public String toString() { return "Bank Account No:"+accountNumber+" balance:"+balance; }}

BankAccount.java

Page 29: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 29

Answer

public class SavingsAccount extends BankAccount { private double interestRate;

public SavingsAccount(double balance, double interestRate) { super(balance); this.interestRate = interestRate; } public void setInterestRate(double rate) { interestRate = rate; } }

SavingsAccount.java

Page 30: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 30

Programming Question

Write a tester class SavingsAccountDemo to test the functionality of SavingsAccount class.

In the main method do following:• Create a savings account object with balance =10000 and

interest rate=2.5• Update the interest rate of savings account to 4.25• Deposit 500• Print the final balance

Sample run:

Page 31: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 31

Answerpublic class SavingsAccountDemo { public static void main(String args[]) { SavingsAccount savingsAcct = new SavingsAccount(10000,2.50); savingsAcct.setInterestRate(4.25); savingsAcct.deposit(500.00); System.out.println("Balance: " +savingsAcct.getBalance()); }}

SavingsAccountDemo.java

Page 32: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 32

Answerpublic class SavingsAccountDemo { public static void main(String args[]) { SavingsAccount savingsAcct = new SavingsAccount(10000,2.50); savingsAcct.setInterestRate(4.25); savingsAcct.deposit(500.00); System.out.println("Balance: " +savingsAcct.getBalance()); }}

SavingsAccountDemo.java

Can we replace this statement by:BankAccount savingsAcct = new SavingsAccount(10000,2.50);

Page 33: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 33

Polymorphism

Polymorphism:

• Ability of an object to take on many forms.

Polymorphism in OOP:

• The most common use:

• A parent class reference is used to refer to a child class object.

Page 34: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 34

Polymorphism

Overloading:

• when two or more methods in the same class have the same name but different parameter types.

• Called static polymorphism.

• Can be determined at compile time E.g

Calculator c = new Calculator();c.add(1,2); //calls method add(int a, int b)c.add(1.25, 2.6) //calls method add(double a, double b)c.add(1,2,6) //calls method add(int a, int b, int c)

Page 35: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 35

Overriding: • when a subclass method provides an implementation of a superclass

method whose parameter variables have the same types.• When overriding a method, the types of the parameter variables

must match exactly.• Called dynamic polymorphism (most popular form of polymorphism)

• Determined at run time E.g

Employee e;e = new SalariedEmployee();// Calls getSalary method in SalariedEmployee class:e.getSalary(); e = new CommissionedEmployee();// Calls getSalary method in CommissionedEmloyee class:e.getSalary()

Page 36: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 36

Overriding Methods

An overriding method can extend or replace the functionality of the superclass method.

Replace: provide completely defiferent implementation

Extend: extend the functionality provided by super class

Page 37: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 37

Syntax 9.2 Calling a Superclass Method

Example of extending functionality of deposit method in SavingsAccount class

Page 38: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 38

Question

Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java?

a. BankAccount account = new SavingsAccount();b. SavingsAccount account2 = new BankAccount();c. BankAccount account = null;

SavingsAccount account2 = account;

Page 39: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 39

Answer

Answer: a only.

Assuming SavingsAccount is a subclass of BankAccount, which of the following code fragments are valid in Java?

a. BankAccount account = new SavingsAccount();b. SavingsAccount account2 = new BankAccount();c. BankAccount account = null; SavingsAccount account2 = account;

Page 40: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 40

Question

If account is a variable of type BankAccount that holds a non-null reference, what do you know about the object to which account refers?

Page 41: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 41

Answer

It belongs to the class BankAccount or one of its subclasses.

Page 42: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 42

Question

What is the super class of PrintStream class n Java class library?

Page 43: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 43

Answer

Class hierarchy

Super class of PrintStream class

Subclasses of PrintStream

Page 44: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 44

Page 45: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 45

Object: The Cosmic Superclass

Every class defined without an explicit extends clause automatically extend Object

The class Object is the direct or indirect superclass of every class in Java.• E.g. Your BankAccount class extends Object class

Some methods defined in Object: • clone - creates and returns a copy of this object (shallow/deep copy).

• toString - yields a string describing the object

• equals - compares objects with each other

• hashCode - yields a numerical code for storing the object in a set

• getClass – return the runtime class of this object

Page 46: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 46

Object: The Cosmic Superclass

Figure 9 The Object Class Is the Superclass of Every Java Class

Page 47: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 47

Overriding the toString Method

Override the toString method in your classes to yield a string that describes the object’s state.• You already did this!

E.g. BankAccount class toString method:public String toString()

{

return "BankAccount[balance=" + balance + "]”;

}

In BankAccountTester:BankAccount momsSavings = new BankAccount(5000);

String s = momsSavings.toString();

// Sets s to "BankAccount[balance=5000]"

Page 48: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 48

Programming Question

Override the toString method in SavingsAccount class so that text returned include accountNumber, balance and interestRate.

BankAccount class: slide 28 Tester class:

public class BankAccountDemo{ public static void main(String args[]){ SavingsAccount savingsAcct = new SavingsAccount(10000,2.50); savingsAcct.setInterestRate(4.25); savingsAcct.deposit(500.00); System.out.println("Balance: " +savingsAcct); }}

Sample output:

Page 49: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 49

Answerpublic class SavingsAccount extends BankAccount { private double interestRate;

public SavingsAccount(double balance, double interestRate){ super(balance); this.interestRate = interestRate; } public double getInterestRate() { return interestRate; }

public void setInterestRate(double rate) { interestRate = rate; } public String toString(){ return super.toString() + " interestRate="+interestRate; }

}

SavingsAccount.java

Page 50: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 50

Overriding the equals Method

equals method checks whether two objects have the same content:if (stamp1.equals(stamp2)) . . . // Contents are the same

== operator tests whether two references are identical - referring to the same object:if (stamp1 == stamp2) . . . // Objects are the same

Page 51: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 51

Overriding the equals Method

Figure 10 Two References to Equal Objects

Page 52: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 52

Overriding the equals Method

Figure 11 Two References to the Same Object

Page 53: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 53

Overriding the equals Method

To implement the equals method for a Stamp class - • Override the equals method of the Object class:

public class Stamp{ private String color; private int value; . . . public boolean equals(Object otherObject) { //your code here } . . .}

Cannot change parameter type of the equals method - it must be Object

Cast the parameter variable to the class Stamp instead: Stamp other = (Stamp) otherObject;

Page 54: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 54

Overriding the equals Method

After casting, you can compare two Stamps

public boolean equals(Object otherObject){ Stamp other = (Stamp) otherObject; return color.equals(other.color) && value == other.value;}

The equals method can access the instance variables of any Stamp object.

The access other.color is legal.

Page 55: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 55

Programming Question

Modify BankAccount class to override equals method.

Modify tester class to call equals method:public class BankAccountDemo{ public static void main(String args[]) { BankAccount savingsAcct1 = new SavingsAccount(10000,2.50);

BankAccount savingsAcct2 = new SavingsAccount(10000,2.50); System.out.println(savingsAcct.equals(savingsAcct2));

System.out.println(savingsAcct.equals(savingsAcct2)); }}

Sample output

Page 56: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 56

Answerpublic class BankAccount{ private double balance; private int accountNumber; private static int lastAssignedNumber = 0; public BankAccount(double initialBalance) { balance = initialBalance; lastAssignedNumber++; accountNumber = lastAssignedNumber; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { balance -= amount; } public double getBalance() { return balance; } public String toString() { return "Bank Account No:"+accountNumber+" balance:"+balance; }

public boolean equals(Object anotherAccount) { BankAccount other = (BankAccount) anotherAccount; return (accountNumber == other.accountNumber) && (balance==other.balance); }

}

Page 57: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 57

Programming Question

Modify your Rectangle.java class so you override the equals method and toString method.

• equals method should return true only if x,y,width and height matches to rectangle in parameter.

• To string method should print the x,y,width and height parameters of object

• Sample output:

Page 58: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 58

Answerpublic class Rectangle{

int x, y, width, height;

public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } /** * overriden equals method * */ public boolean equals(Object object) { Rectangle r = (Rectangle)object; if(x==r.x && y==r.y && width==r.width && height==r.height) return true; return false; } public String toString() { return "Rectangle [x:"+x+" y:"+y+" width:"+width+" height:"+height+"]"; } public static void main(String args[]) { Rectangle r1 = new Rectangle(10,20,50,50); Rectangle r2 = new Rectangle(10,20,50,50); Rectangle r3 = new Rectangle(10,50,50,50); System.out.println("r1= "+r1); System.out.println("r2= "+r2); System.out.println("r3= "+r3); System.out.println("r1.equals(r2)"+r1.equals(r2)); System.out.println("r1.equals(r3)"+r1.equals(r3)); }}

Page 59: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 59

The instanceof Operator

It is legal to store a subclass reference in a superclass variable:

BankAccount acct1 = new SavingsAccount(1000.0, 2.5);

Object obj = acct; // OK

Sometimes you need to convert from a superclass reference to a subclass reference.

• If you know a variable of type Object actually holds a SavingsAcount reference, you can cast

SavingsAccount acct1 = (SavingsAccount) obj;

If obj refers to an object of an unrelated type, “class cast” exception is thrown.

Page 60: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 60

The instanceof Operator

The instanceof operator tests whether an object belongs to a particular type.

obj instanceof BankAccount

Using the instanceof operator, a safe cast can be programmed as follows:

if (obj instanceof BankAccount){ BankAccount acct1 = (BankAccount) obj;}

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Page 61: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 61

Question

Will the following code fragment compile? Will it run? If not,

what error is reported?Object obj = "Hello";

System.out.println(obj.length());

Page 62: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 62

Answer

Answer: The second line will not compile. The class Object does not have a method length.

Page 63: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 63

Question

Assuming that x is an object reference, what is the value of x instanceof Object?

Page 64: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 64

Answer

Answer: The value is false if x is null and true otherwise.

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Page 65: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 6565

When Not to Use Inheritance Inheritance is appropriate when:

• the new class “is a” particular case of the old class :

• The subclass must have every property of the superclass.

• E.g.

– A Car is a Vehicle.

– A SavingsAccount is an Account.

Inheritance is inappropriate when:

• the words “is a” don’t fit.

• E.g.

• it wouldn’t make sense to say that a SavingsAccount is a Vehicle.

Page 66: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 66

Abstract Classes When you extend an existing class, you have the

choice whether or not to override the methods of the superclass.

Sometimes, it is desirable to force programmers to override a method.

That happens when there is no good default for the superclass, and only the subclass programmer can know how to implement the method properly.

Page 67: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 67

Abstract Classes E.g. Suppose we decides that every account type must have some

monthly fees. • Therefore, a deductFees method should be added to the

BankAccount class:

But what should the method do?

• We could have the method do nothing. • But then a programmer implementing a new subclass might

simply forget to implement the deductFees method:• new account would inherit the do-nothing method of the

superclass.

There is a better way:• declare the deductFees method as an abstract method

Page 68: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 68

Abstract Classes An abstract method has no implementation.

This forces the implementers of subclasses to specify concrete implementations of this method.

You cannot construct objects of classes with abstract methods.

A class for which you cannot create objects is called an abstract class.

A class for which you can create objects is sometimes called a concrete class.

Page 69: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 69

Abstract Classes

In Java, you must declare all abstract classes with the reserved word abstract:

Which classes must be declared abstract?1. A class that declares an abstract method2. A class that inherits an abstract method without

overriding it3. Optionally, if you want, declare classes with no abstract

methods as abstract. • Doing so prevents programmers from creating instances of that

class but allows them to create their own subclasses.

Page 70: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 70

Abstract Classes

You CANNOT construct an object of an abstract class

you can still have a variable whose type is an abstract class.

• Actual object to which it refers must be an instance of a concrete subclass

Page 71: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 71

public abstract class Employee{ private String name; private String address; private int number;

public Employee(String name, String address, int number) { this.name = name; this.address = address; this.number = number; } public abstract double computePay();

public String toString() { return name + " " + address + " " + number; }}

Employee.java

Page 72: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 72

public class SalariedEmployee extends Employee { private double weeklySalary; public SalariedEmployee(String name, String address, int number, double

weeklySalary) { super(name,address,number); this.weeklySalary = weeklySalary; } public double computePay() { return this.weeklySalary*2; } }

SalaredEmployee.java

If SalariedEmployee did not override any inherted abstract methods it has be declared an abstract class

Page 73: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 73

Abstract Classes

Why use abstract classes?

• To force programmers to create subclasses.

• By specifying certain methods as abstract you avoid the trouble of coming up with useless default methods that others might inherit by accident.

abstract classes can have:

• instance variables,

• concrete methods and

• constructors.

Page 74: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 74

Programming Question

Implement the abstract class Shape:• Instance variables: color• Constructor: 1-arg constructor that initaize color• Instance method: toString that print “ Shape of color=…”• Abstract method: getArea that return area of the shape

Subclass Rectangle:• Instance variables: length, width• Constructor: 3-arg constructor that initaize

color,length,width• Instance method: override toString to print instance

variable values• method: overrde getArea that return area of the Rectangle

Page 75: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 75

Answerpublic abstract class Shape { private String color; public Shape (String color) { this.color = color; } @Override public String toString() { return "Shape of color=" + color; } public abstract double getArea(); }

Shape.java

Page 76: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 76

public class Rectangle extends Shape { private int length; private int width; public Rectangle(String color, int length, int width) { super(color); this.length = length; this.width = width; } @Override public String toString() { return "Rectangle of length=" + length + " and width=" + width + ",

subclass of " + super.toString(); } @Override public double getArea() { return length*width; }}

Rectangle.java

Page 77: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 77

public class Triangle extends Shape { private int base; private int height; public Triangle(String color, int base, int height) { super(color); this.base = base; this.height = height; } @Override public String toString() { return "Triangle of base=" + base + " and height=" + height + ", subclass

of " + super.toString(); } @Override public double getArea() { return 0.5*base*height; }}

Triangle.java

Page 78: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 78

public class TestShape { public static void main(String[] args) { Shape s1 = new Rectangle("red", 4, 5); System.out.println(s1); System.out.println("Area is " + s1.getArea()); Shape s2 = new Triangle("blue", 4, 5); System.out.println(s2); System.out.println("Area is " + s2.getArea()); // Cannot create instance of an abstract class //Shape s3 = new Shape("green"); // Compilation Error!! }}

TestShape.java

Page 79: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 79

Final Methods and Classes Occasionally, you may want to prevent other programmers from

creating subclasses or from overriding certain methods.

• Opposite of abstract methods

In these situations, you use the final reserved word

E.g. String class in Java library is final:

• i.e. nobody can extend (create subclasses of) the String class

Page 80: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 80

You can also declare individual methods as final:

All extending subclasses cannot override the checkPassword method with another method that simply returns true.

Class is not final

Page 81: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 81

Common Error

Overriding Methods to Be Less Accessible

If a superclass declares a method to be publicly accessible, you cannot override it to be more private in a subclass.

E.g. superclass: BankAccount

E.g subclass: CheckingAccount

• The compiler does not allow this

Page 82: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 82

Enumeration Types

In many programs, you use variables that can hold one of a finite number of values:

• E.g in TaxReturn class, status variable:

• Only could hold one of the values SINGLE or MARRIED.

• We arbitrarily declared SINGLE as the number 1 and MARRIED as 2.

If, due to some programming error, the status variable is set to another integer value (such as –1, 0, or 3), then the programming logic may produce invalid results.

In a simple program, this is not really a problem.

But as programs grow over time, and more cases are added (such as the “married filing separately” and “head of household” categories), errors can slip in.

Page 83: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 83

Java version 5.0 introduces a remedy: enumeration types.

An enumeration type has a finite set of values E.g.

You can have any number of values, but you must include them all in the enum declaration.

You can declare variables of the enumeration type:

Use the == operator to compare enumeration values:

Page 84: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 84

It is common to nest an enum declaration inside a class: E.g.

To access the enumeration outside the class in which it is declared, use the class name as a prefix:

Page 85: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 85

Page 86: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 86

An enumeration type variable can be null. E.g.

• the status variable in the previous example can actually have three values:

• SINGLE, MARRIED, and null.

Page 87: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 87

Programming Question

Declare a new class FilingStatus.java with following code:

public enum FilingStatus{SINGLE, MARRIED}

Modify the TaxReturn class to do the following:• Declare getTax() method final• Modify class to use FilingStatus for status.

/net/people/classes/CS160/handouts/horstmann_bigjava_source_code/ch05/section_4

Page 88: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 88

Answer

public enum FilingStatus{SINGLE, MARRIED}

FilingStatus.java

Page 89: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 89

1 import java.util.Scanner;2 /**3 A tax return of a taxpayer in 2008.4 */5 public class TaxReturn6 { 7 private static final double RATE1 = 0.10;8 private static final double RATE2 = 0.25;9 private static final double RATE1_SINGLE_LIMIT = 32000;10 private static final double RATE1_MARRIED_LIMIT = 64000;1112 private double income;13 private FilingStatus status;1415 /**16 Constructs a TaxReturn object for a given income and 17 marital status.18 @param anIncome the taxpayer income19 @param aStatus either SINGLE or MARRIED20 */ 21 public TaxReturn(double anIncome, FilingStatus aStatus)22 { 23 income = anIncome;24 status = aStatus;25 }26

TaxReturn.java

CONTINUED..

Page 90: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 90

27 public final double getTax()28 { 29 double tax1 = 0;30 double tax2 = 0;3132 if (status == FilingStatus.SINGLE)33 { 34 if (income <= RATE1_SINGLE_LIMIT)35 {36 tax1 = RATE1 * income;37 }38 else39 {40 tax1 = RATE1 * RATE1_SINGLE_LIMIT;41 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);42 }43 }44 else45 { 46 if (income <= RATE1_MARRIED_LIMIT)47 {48 tax1 = RATE1 * income;49 }50 else 51 {52 tax1 = RATE1 * RATE1_MARRIED_LIMIT;53 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT);54 }55 }5657 return tax1 + tax2;58 }

Page 91: Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Inheritance

Copyright © 2014 by John Wiley & Sons. All rights reserved. 91

59 60 public static void main(String[] args)61 { 62 Scanner in = new Scanner(System.in);6364 System.out.print("Please enter your income: ");65 double income = in.nextDouble();6667 System.out.print("Are you married? (Y/N) ");68 String input = in.next();69 FilingStatus status;70 if (input.equals("Y")) 71 {72 status = FilingStatus.MARRIED;73 }74 else 75 {76 status = FilingStatus.SINGLE;77 }7879 TaxReturn aTaxReturn = new TaxReturn(income, status);8081 System.out.println("Tax: “ + aTaxReturn.getTax());83 }84}