0% found this document useful (0 votes)
1 views

Lecture_06_Inheritance

The document provides an overview of Java class inheritance, detailing the relationships between superclasses and subclasses, the concept of constructors in subclasses, method overriding, and access modifiers. It emphasizes the benefits of inheritance in software development, such as code reuse and specialization. Additionally, it discusses the implications of protected members and the importance of encapsulation in object-oriented programming.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Lecture_06_Inheritance

The document provides an overview of Java class inheritance, detailing the relationships between superclasses and subclasses, the concept of constructors in subclasses, method overriding, and access modifiers. It emphasizes the benefits of inheritance in software development, such as code reuse and specialization. Additionally, it discusses the implications of protected members and the importance of encapsulation in object-oriented programming.

Uploaded by

urbanatuba
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Java Class

Inheritance
CSIT213 Java Programming
Overview
• Superclasses and Subclasses

• Class relationship: Inheritance Vs. Composition

• Constructor in Subclass

• Override Methods

• Protected data fields

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.

 Can save time during program development by basing new


classes on existing proven and debugged high-quality software.

 Increases the likelihood that a system will be implemented and


maintained effectively.

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

• Is-a represents inheritance


In an is-a relationship, an object of a subclass can also be treated as an
object of its superclass.
• Has-a represents an aggregation
In a has-a relationship, an object contains as members references
to other objects.

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 Employee(int number, String name, String address) {


this.number = number;
this.name = name;
this.address = address;
}

public String toString() {


return String.format("Number: %d\nName: %s\nAddress: %s", number,
name, address);
}
}
11
Subclass Admin
class Admin extends Employee { Directly inherits from the superclass Employee
private String skills;
private double salary; More attributes in the subclass

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

public String toString() {


return String.format("%s\nSkills: %s\nSalary: %.2f", super.toString(), skills,
salary);
}
}

12
Subclass Tech
class Tech extends Employee {
private String speciality;

public Tech(int number, String name, String address, String spec) {


super(number, name, address);
speciality = spec;
}

public String toString() {


return String.format("%s\nSpeciality: %s", super.toString(), 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;
}

public String toString() {


return String.format("%s\nStart date: %s\nEnd date: %s\nSalary: %.2f",
super.toString(), startDate, endDate, 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

public Employee(int number, String name, String address) {


this.number = number;
this.name = name;
this.address = address;
}

public int getNumber() {


return number;
}

public String toString() {


return String.format("Number: %d\nName: %s\nAddress: %s", number, name, address);
}
}

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

public Tech(int number, String name, String address, String spec) {


super(number, name, address);
speciality = spec;
Constructor cannot be inherited.
}
Call the superclass constructor.

@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;
}

public double getPayment() {


return hourlyRate * hours;
}

public String toString() {


return String.format("Number: %d\nName: %s\nAddress: %s\nSpeciality: %s\nHourly
rate: %.2f\nHours: %.2f\nPayment: %.2f", number, name, address, speciality, hourlyRate, hours,
getPayment());
}
}
26
Same package different classes
Different class in the
public class testEmployee1{
same file (package)
public void test() {
ArrayList<Employee> emps = new ArrayList<Employee>();

Employee e = new Admin(12345, "Alice", "1 Northfields ave Wollongong", "read


write", 85000.5);
emps.add(e);

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

Define inheritance packages


Define the class Employee in a
package employee;
package employee

public class Employee {


protected int number;
protected String name;
protected String address;

public Employee(int number, String name, String address) {


this.number = number;
this.name = name;
this.address = address;
}

}

28
testEmployee2/employee/Admin.java

Define the subclass in the same package


package employee;

public 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;
this.salary = salary;
}

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 direct and indirect superclasses

29
testEmployee2/testEmployee2.java

Different packages and different classes


import employee.*;

public class testEmployee2{


public void test() {
ArrayList<Employee> emps = new ArrayList<Employee>();

Employee e = new Admin(12345, "Alice", "1 Northfields ave Wollongong",


"read write", 85000.5);
emps.add(e);

for(Employee v:emps) {
System.out.println(v.toString());
Cannot access
System.out.println("Name: " + v.name);
protected
}
attribute
}


}
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

You might also like