Lecture_06_Inheritance
Lecture_06_Inheritance
Inheritance
CSIT213 Java Programming
Overview
• Superclasses and Subclasses
• Constructor in Subclass
• Override Methods
2
Motivation
• Instead of starting from scratch, a new class is created by acquiring an
existing class’s members and possibly embellishing them with new or
modified capabilities.
3
Introduction
• When creating a class, rather than declaring completely new members, you
can designate that the new class should inherit the members of an existing
class.
- Existing class is the superclass
- New class is the subclass
• A subclass can be a superclass of future subclasses.
• A subclass can add its fields and methods.
• A subclass is more specific than its superclass and represents a more specialized
group of objects.
• The subclass exhibits the behaviors of its superclass and can add behaviors that
are specific to the subclass. That is why the inheritance is sometimes referred to
as specialization.
4
Class inheritance diagrams
Superclass
Subclasses
5
Introduction
• The direct superclass is the superclass from which the subclass explicitly
inherits.
• An indirect superclass is any class above the direct superclass in the class
hierarchy.
• The Java class hierarchy begins with class Object (in package java.lang)
- Every class in Java directly or indirectly extends (or “inherits from”) the
Object class.
• Java supports only single inheritance, in which each class is derived from
exactly one direct superclass.
6
Is-a and has-a relationships
7
Superclass and subclass
• Objects of all classes that extend a common superclass can be treated as
objects of that superclass.
- Commonality is expressed in the members of the superclass.
• Inheritance issue
- A subclass can inherit methods that it does not need or should not have.
- Even when a superclass method is appropriate for a subclass, that
subclass often needs a customized version of the method.
- The subclass can override (redefine) the superclass method with an
appropriate implementation.
8
Accessibilities
• A class’s public members are accessible wherever the program has a
reference to an object of that class or one of its subclasses.
• A class’s private members are accessible only within the class itself.
– They can be accessed only through the public or protected
methods inherited from the superclass
• Subclass methods can refer to public and protected members
inherited from the superclass simply by using the member names.
• When a subclass method overrides an inherited superclass method, the
superclass version of the method can be accessed from the subclass by
preceding the method name with keyword super and a dot (.).
9
Class inheritance hierarchy
Direct superclass of Admin and Tech.
Indirect superclass of Contractor and Casual
10
testEmployee.java
Superclass Employee
class Employee {
private int number;
private String name;
private String address;
public Admin(int number, String name, String address, String skills, double salary)
{
super(number, name, address); Call the superclass constructor
this.skills = skills;
this.salary = salary; Access the method
} of the superclass
12
Subclass Tech
class Tech extends Employee {
private String speciality;
13
Subclass Contractor
Directly inherits from the superclass
class Contractor extends Tech {
Tech, not from the class Employee
private String startDate;
private String endDate;
private double salary;
public Contractor(int number, String name, String address, String spec, String start,
String end, double salary) {
super(number, name, address, spec);
startDate = start;
endDate = end;
this.salary = salary;
}
14
Subclass Casual
class Casual extends Tech {
private double hourlyRate;
private double hours;
public Casual(int number, String name, String address, String spec, double hr, double h)
{
super(number, name, address, spec);
hourlyRate = hr;
hours = h;
}
public double getPayment() {
return hourlyRate * hours;
}
public String toString() {
return String.format("%s\nHourly rate: %.2f\nHours: %.2f\nPayment: %.2f",
super.toString(), hourlyRate, hours, getPayment());
}
}
15
Super class reference
ArrayList<Employee> emps = new ArrayList<Employee>();
Employee e = new Admin(12345, "Alice", "1 Northfields ave Wollongong", "read write",
85000.5);
emps.add(e);
e = new Contractor(22345, "Bob", "1 Ocean road Wollongong", "Java C++", "1/1/2020",
"31/12/2022", 95000.5);
emps.add(e);
e = new Admin(32345, "Kate", "1 Moore street Wollongong", "read write", 85000.5);
emps.add(e);
e = new Casual(42345, "Peter", "1 Cliff street Wollongong", "Python Java C++", 72.5, 35);
emps.add(e);
for(Employee v:emps)
System.out.println(v.toString()); Which toString()
method belongs to?
16
Constructors in the class inheritance
• Constructors are not inherited.
• The first statement of a subclass constructor is to call its direct
superclass’s constructor explicitly or implicitly.
– Ensures that the instance variables inherited from the superclass
are initialized properly.
• If the code does not include an explicit call to the superclass constructor, Java
implicitly calls the superclass’s default constructor.
• A subclass’s default constructor calls the superclass’s default constructor.
17
Constructors in subclasses
• Instantiating a subclass object begins a chain of constructor calls.
– The subclass constructor, before performing its tasks, explicitly uses
super to call one of the constructors in its direct superclass or
implicitly calls the superclass’s default or no-argument constructor.
• If the superclass is derived from another class, the superclass constructor
invokes the constructor of the next class up the hierarchy, and so on.
• The last constructor called in the chain is always Object’s constructor,
but the Object’s constructor is the first to be implemented. Original
subclass constructor’s body finishes executing last.
• Each superclass’s constructor manipulates the superclass instance
variables that the subclass object inherits.
18
Override method
• To override a superclass method, a subclass must declare a method
with the same signature as the superclass method.
@Override
Indicates that a method should override a superclass method with the
same signature.
• The method toString() is one of the methods that every class inherits
directly or indirectly from the class Object.
19
Protected members
An intermediate level of access between public and private.
• A superclass’s protected members can be accessed by members of that
superclass, by members of its subclasses and by members of other
classes in the same package.
• Protected members also have package access.
• All public and protected superclass members retain their original access
modifier when they become members of the subclass.
• With protected instance variables, the subclass gets access to the
instance variables. Classes that are not subclasses and classes that are
not in the same package cannot access these variables directly.
20
Employee inheritance hierarchy
Modify attributes of
superclasses to
protected
21
testEmployee1.java
Superclass Employee
class Employee {
protected int number;
protected String name; Modify the attributes of the
protected String address; superclass to protected
22
Subclass Admin
class Admin extends Employee {
private String skills;
private double salary;
public Admin(int number, String name, String address, String skills, double salary) {
super(number, name, address);
this.skills = skills; Constructor cannot be inherited.
this.salary = salary; Call the superclass constructor.
}
@Override
public String toString() {
return String.format("Number: %d\nName: %s\nAddress: %s\nSkills: %s\nSalary:
%.2f", number, name, address, skills, salary);
}
Subclass method can access
}
protected attributes of the superclass
23
Subclass Tech
class Tech extends Employee {
Modify the attributes of the
protected String speciality; superclass to protected
@Override
public String toString() {
return String.format("Number: %d\nName: %s\nAddress: %s\nSpeciality: %s",
number, name, address, speciality);
}
} Subclass method can access protected
attributes of the superclass
24
Subclass Contractor
class Contractor extends Tech {
private String startDate;
private String endDate;
private double salary;
public Contractor(int number, String name, String address, String spec, String start,
String end, double salary) {
super(number, name, address, spec);
startDate = start;
endDate = end;
this.salary = salary;
}
@Override
public String toString() {
return String.format("Number: %d\nName: %s\nAddress: %s\nSpeciality: %s\nStart
date: %s\nEnd date: %s\nSalary: %.2f", number, name, address, speciality, startDate,
endDate, salary);
}
} Subclass method can access protected
attributes of the direct and indirect superclasses
25
Subclass Casual
class Casual extends Tech {
private double hourlyRate;
private double hours;
public Casual(int number, String name, String address, String spec, double hr, double h)
{
super(number, name, address, spec);
hourlyRate = hr;
hours = h;
}
for(Employee v:emps) {
System.out.println(v.toString());
System.out.println("Name: " + v.name);
}
}
… Can access the
protected attribute
}
27
testEmployee2/employee/Employee.java
28
testEmployee2/employee/Admin.java
public Admin(int number, String name, String address, String skills, double salary) {
super(number, name, address);
this.skills = skills;
this.salary = salary;
}
29
testEmployee2/testEmployee2.java
…
}
30
Protected accessibility
• Inheriting protected attributes enables direct access to the members by
subclasses.
• In most cases, use private attributes unless you have good reason not to.
– Encourage proper software engineering.
– Code will be easier to maintain, modify and debug.
• Using protected attributes creates several potential problems.
– It breaks encapsulation.
– It may not be flexible.
• Avoid public attributes except for constants.
31