Inheritance
Copyright © 2014 by John Wiley & Sons. All rights reserved.
1
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
2
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
Vehicle
Motorcycle
Car
Sedan
Truck
SUV
Figure 1 An Inheritance Hierarchy of Vehicle Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3
Inheritance Hierarchies
 The class Car inherits from the class Vehicle
 The Vehicle class is the superclass
 The Car class is the subclass
Superclass
Subclass
Figure 2 Inheritance Diagram
Copyright © 2014 by John Wiley & Sons. All rights reserved.
4
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:
Employee
-name
-Id
+getSalary()
+getName()
Add new functionality
Use inherited functionality
Override inherited functionality (modify)
SalariedEmployee
-weeklySalary
+calculateBonus()
Copyright © 2014 by John Wiley & Sons. All rights reserved.
CommissionEmployee
-grossSales
-commissionRate
+getCommissionRate()
5
parent/supercalss of
SalariedEmployee class and
CommissionEmployee
Employee
-name
-Id
+getSalary()
Inherited + overridden by subclasses
+getName()
Inherited and used as it is by subclasses
+setID(id)
Inherited and used as it is by subclasses
Additional attributes
SalariedEmployee
Additional methods
-weeklySalary
+calculateBonus()
Copyright © 2014 by John Wiley & Sons. All rights reserved.
CommissionEmployee
-grossSales
-commissionRate
+getCommissionRate()
6
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
7
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
{
…
}
Superclass of Car
Subclass of Vehicle
Copyright © 2014 by John Wiley & Sons. All rights reserved.
8
Writing a Subclass Example
Superclass:
Public class Employee
{
private String name;
private int id;
public
public
public
public
Employee.java
Employee(String name, int id){this.name=name; this.id=id;}
double getSalary(){return 2000.0;}
String getName(){ return name;}
void setId(int id){ this.id = id;}
}
Subclass:
Public class SalariedEmployee extends Employee
{
private double weeklySalary;
SalariedEmployee.java
public double getSalary(){return this.weeklySalary*4;}
public double calculateBonus(){return this.weeklySalary*0.5; }
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
9
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
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);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Employee
-name
-Id
+getSalary()
+getName()
+setID(id)
SalariedEmployee
-weeklySalary
+calculateBonus()
CommissionEmployee
-grossSales
-commissionRate
+getCommissionRate() 12
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
+calculateBonus()
CommissionEmployee
-grossSales
-commissionRate
+getCommissionRate() 13
 The substitution principle:
• You can always use a subclass object when a superclass object
is expected.
Person
Employee
SalariedEmployee
Employee
emp =
CommissionEmployee
new SalariedEmployee();
Person person = new SalariedEmployee();
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Question
Consider classes Manager and Employee. Which should
be the superclass and which should be the subclass?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
15
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
Question
What are the inheritance relationships between classes
BankAccount, CheckingAccount, and
SavingsAccount?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
Answer
CheckingAccount and SavingsAccount both inherit
from the more general class BankAccount.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
18
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
Sedan
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Truck
SUV
19
Answer
doSomething(Car c)
Vehicle
Motorcycle
Car
Sedan
Truck
SUV
Answer: Vehicle, Truck, Motorcycle
Copyright © 2014 by John Wiley & Sons. All rights reserved.
20
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
21
Writing Subclass Constructors
 A first attempt at writing the constructor:
public class SalariedEmployee extends Employee
{
double weeklySalary;
}
public SalariedEmployee(String empName, int empId, double empWeekSal)
{
name = empName;
id = empId;
weeklySalary = empWeekSal;
}
Is above an OK way to write subclass constructor?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
22
 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;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
23
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
24
Writing Subclass Constructors
 What if subclass constructor fails to call super?
public SalariedEmployee(String empName, int empId, double empWeekSal)
{
weeklySalary = empWeekSal;
}
• Then the compiler will automatically insert super() at the
beginning of the constructor.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
25
25
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
26
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 
Copyright © 2014 by John Wiley & Sons. All rights reserved.
27
BankAccount.java
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
Answer
SavingsAccount.java
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
29
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:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
Answer
SavingsAccountDemo.java
public 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());
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
31
Answer
SavingsAccountDemo.java
public 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());
}
}
Can we replace this statement by:
BankAccount savingsAcct = new SavingsAccount(10000,2.50);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
32
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
33
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)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
 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()
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
36
Syntax 9.2 Calling a Superclass Method
Example of extending functionality of deposit method in SavingsAccount class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
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;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
38
Answer
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;
Answer: a only.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
39
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?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
Answer
It belongs to the class BankAccount or one of its subclasses.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
Question
 What is the super class of PrintStream class n Java
class library?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
42
Answer
Class hierarchy
Super class of PrintStream class
Subclasses of PrintStream
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
45
Object: The Cosmic Superclass
Figure 9 The Object Class Is the Superclass of Every Java
Class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
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]"
Copyright © 2014 by John Wiley & Sons. All rights reserved.
47
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:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
48
Answer
SavingsAccount.java
public 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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
50
Overriding the equals Method
Figure 10 Two References to Equal Objects
Copyright © 2014 by John Wiley & Sons. All rights reserved.
51
Overriding the equals Method
Figure 11 Two References to the Same Object
Copyright © 2014 by John Wiley & Sons. All rights reserved.
52
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;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
53
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
54
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
55
Answer
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)
public void withdraw(double amount)
public double getBalance()
{
{
{
{
balance += amount;
}
balance -= amount;
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);
}
Copyright
© 2014 by John Wiley & Sons. All rights reserved.
}
56
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:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
Answer
public 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));
}
Copyright © 2014 by John Wiley
& Sons. All rights reserved.
}
58
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
59
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
60
Question
Will the following code fragment compile? Will it run? If not,
what error is reported?
Object obj = "Hello";
System.out.println(obj.length());
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
Answer
Answer: The second line will not compile. The class
Object does not have a method length.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
Question
Assuming that x is an object reference, what is the value of
x instanceof Object?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
63
Answer
Answer:
The value is false if x is null and true otherwise.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Copyright © 2014 by John Wiley & Sons. All rights reserved.
64
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
65
65
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
66
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
67
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
68
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 method
2. A class that inherits an abstract method without
overriding it
3. 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
69
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
70
Employee.java
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
71
SalaredEmployee.java
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
If SalariedEmployee did not override any
inherted abstract methods it has be declared
an abstract class
72
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
73
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
74
Answer
Shape.java
public 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();
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
75
Rectangle.java
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
76
Triangle.java
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;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
77
TestShape.java
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!!
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
78
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
79
 You can also declare individual methods as final:
Class is not final
 All extending subclasses cannot override the
checkPassword method with another method that
simply returns true.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
80
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
Copyright © 2014 by John Wiley & Sons. All rights reserved.
81
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
82
 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:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
83
 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:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
84
Copyright © 2014 by John Wiley & Sons. All rights reserved.
85
 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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
86
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_c
ode/ch05/section_4
Copyright © 2014 by John Wiley & Sons. All rights reserved.
87
Answer
FilingStatus.java
public enum FilingStatus{SINGLE, MARRIED}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
88
TaxReturn.java
1 import java.util.Scanner;
2 /**
3
A tax return of a taxpayer in 2008.
4 */
5 public class TaxReturn
6 {
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;
11
12
private double income;
13
private FilingStatus status;
14
15
/**
16
Constructs a TaxReturn object for a given income and
17
marital status.
18
@param anIncome the taxpayer income
19
@param aStatus either SINGLE or MARRIED
20
*/
21
public TaxReturn(double anIncome, FilingStatus aStatus)
22
{
23
income = anIncome;
24
status = aStatus;
25
}
26
CONTINUED..
Copyright © 2014 by John Wiley & Sons. All rights reserved.
89
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public final double getTax()
{
double tax1 = 0;
double tax2 = 0;
if (status == FilingStatus.SINGLE)
{
if (income <= RATE1_SINGLE_LIMIT)
{
tax1 = RATE1 * income;
}
else
{
tax1 = RATE1 * RATE1_SINGLE_LIMIT;
tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT);
}
}
else
{
if (income <= RATE1_MARRIED_LIMIT)
{
tax1 = RATE1 * income;
}
else
{
tax1 = RATE1 * RATE1_MARRIED_LIMIT;
tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT);
}
}
return tax1 + tax2;
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
90
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
83
84}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter your income: ");
double income = in.nextDouble();
System.out.print("Are you married? (Y/N) ");
String input = in.next();
FilingStatus status;
if (input.equals("Y"))
{
status = FilingStatus.MARRIED;
}
else
{
status = FilingStatus.SINGLE;
}
TaxReturn aTaxReturn = new TaxReturn(income, status);
System.out.println("Tax: “ + aTaxReturn.getTax());
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
91