Chapter 5 - Inheritance
Chapter 5 - Inheritance
Inheritance
By
En. Mohd Nizam bin Osman
(Senior Lecturer)
Department of Computer Science
Faculty of Computer and Mathematical Science, UiTM
Perlis
Objectives
• By the end of this chapter, students should be able to:
Explore the derivation of new classes (sub classes) from existing ones (superclass).
+
o r u t e
avi r i b
e h
Smoking
A tt
Dress (modern, traditional)
Bshopping w
N ew N e
4
Introduction
(Basic Concepts)
• In OOP, Inheritance is a mechanism
that enables one class to inherit both
attributes and behaviours.
The classes you create can inherit data
and methods from existing classes and
at the same time, you can add extra
data and methods to newly created
classes. 5
Introduction
(Basic Concepts)
y? u
Person
sa o
name
n oy
ca t d
name
ha
studentNumber name
Student Employee employeeNumber
W
8
Inheritance
• Inheritance can be defined as the process of creating new classes
from existing classes by absorbing all their attributes and
behaviors and adding new attributes and behaviors to the newly
created classes.
• The sub class inherits all the attributes (data members) and methods
(method members) of the super class automatically.
9
Inheritance
• The general syntax of deriving a class from a existing class is:
modifier class DerivedClassName extends BaseClassName
{
Declarations_of_Added_Instance_Variables
Definitions_of_Added__And_Changed_Methods
}
Student
New Data
-studentNumber: int
member
+Student()
+Student(String, int)
+reset(String, int): void
+setStudentNumber(int): void
+getStudentNumber(): int
New method +writeOutput(): void
members +equals(Student): boolean
12
Inheritance
(Example)
public class Person
{
private String name;
public Person()
{
name = "No name yet";
}
public Person(String initialName)
{
name = initialName;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
} 13
Inheritance
(Example)
public void writeOutput()
{
System.out.println("Name: " + name);
}
public boolean hasSameName(Person otherPerson)
{
return this.name.equalsIgnoreCase(otherPerson.name);
}
}
14
Inheritance
(Example)
public class Student extends Person
{
private int studentNumber;
public Student()
{
super();
studentNumber = 0;//Indicating no number yet
}
public Student(String initialName, int initialStudentNumber)
{
super(initialName);
studentNumber = initialStudentNumber;
}
public void reset(String newName, int newStudentNumber)
{
setName(newName);
studentNumber = newStudentNumber;
}
15
Inheritance
(Example)
public int getStudentNumber()
{
return studentNumber;
}
public void setStudentNumber(int newStudentNumber)
{
studentNumber = newStudentNumber;
}
public void writeOutput()
{
System.out.println("Name: " + getName());
System.out.println("Student Number: " + studentNumber);
}
public boolean equals(Student otherStudent)
{
return this.hasSameName(otherStudent) &&
(this.studentNumber ==
otherStudent.studentNumber);
}
}
16
Inheritance
(Example)
public class InheritanceDemo
{
public static void main(String[] args)
setName() is inherited from
{ the class Person.
Student s = new Student();
s.setName(“Mus Ali");
s.setStudentNumber(1234);
s.reset(“Mustafa Ali”, 123456);
s.writeOutput();
}
}
Sample of Output:
Name: Mustafa Ali
Student Number: 123456
17
Inheritance
• The following facts about superclass and subclass should be kept in
mind:
The private members of the superclass are private to the superclass; hence, the members of the
subclass cannot directly access them. In another words, when you write the definitions of the methods
of the subclass, you cannot directly access the private members of the superclass.
The subclass can directly access the public members of the superclass.
The subclass can override, that is, redefine the public method of the superclass. That is, in the
subclass, you can have a method with the same name, number, and types of parameters as a method
in the superclass. However, this redefinition applies only to the object of the subclass, not to the objects
of the superclass.
All data members of the superclass are also data members of the subclass. Similarly, the methods of
the superclass (unless overridden) are also the method of the subclass. 18
Inheritance
• Inheritance can be either single or multiple.
Person
Single Inheritance
(Student inherits from Person)
Student
Employee Student
Multiple Inheritance
(Staff inherits from Student
Staff and Employee)
22
Access Modifier
(Access from Outside class’s Package)
23
Inheritance – Analysis
(private instance variable of a Super
Class)
• private instance variables in a super class are not inherited by a
sub class; they cannot be referenced directly by name within a
derived class.
• Example:
public void reset(String newName, int newStudentNumber)
{
setName(newName); Valid definition
studentNumber = newStudentNumber;
}
CONCEPT
A sub class cannot access the private
instance variables of its base class directly
by name. It knows only about the public
behaviour of the base class.
25
Inheritance – Analysis
(private method of a Super Class)
• A sub class cannot call a private method defined
within the base class.
CONCEPT
private methods are not
directly accessible from sub
classes
27
Inheritance – Analysis
(Overriding Method Definition)
• In a sub class, if you include a method definition that has the
same name, the exact same number and types of
parameters, and the same return type as a method already in
the base class, this new definition replaces the old definition of
the method when objects of the derived class receive a call to
the method.
Thus the methods use overloading because the two getName() methods
have different numbers of parameters.
31
Inheritance – Analysis
(The final Modifier)
• If you want to specify that a method definition cannot
be overridden by a new definition within a sub class,
you can add the final modifier to the method
heading.
• Example:
32
Inheritance – Analysis
(Constructor in Sub Class)
• When defining a constructor for a sub class, you can use
super as a name for the constructor of the base class.
• Example:
public Student(String initialName, int initialStudentNumber)
{
super(initialName);
studentNumber = initialStudentNumber;
}
33
Inheritance – Analysis
(Constructor in Sub Class)
• When you omit a call to the base-class constructor in any sub
class constructor, the default constructor of the base class is
called as the first action in the new constructor.
• Example:
public Student() public Student()
{ {
studentNumber = 0; = super();
} studentNumber = 0;
}
34
Inheritance – Analysis
(The this Method)
• Another common action when defining a constructor is to call
another constructor in the same class.
• Example:
In this way, the default
public Person() constructor calls the
{ constructor in the same class
this("No name yet");
}
• Syntax:
super.Overridden_Method_Name(Argument_List)
• Example:
Calls writeOutput() in
public void writeOutput() the base/super class
{
super.writeOutput();
System.out.println("Student Number: " + studentNumber);
}
36
Inheritance – Analysis
(Calling Method)
• In general, when writing the definition of the methods of a sub class to
specify a call to a public method of a super class, you do the following:
1
If the sub class overrides a public method of a super class, then
you specify a call to that public method of the superclass by using
the reserved word super followed by dot operator followed by
method name with an appropriate parameter list
2
If the sub class does not override a public method of the super
class, you can specify a call to that public method by using the
name of the method and an appropriate parameter list.
37
Advantages
Software
reusability
Rapid Increased
prototyping reliability
Advantages
Software Code
components sharing
Consistency
of interface
38
Constructing Super Class and Sub Class
(Example 1)
Rectangle
-width: double super class
-length: double
+Rectangle()
+Rectangle(double, double)
+setWidth(double): void sub class
+setLength(double): void
+getWidth(): double
+getLength(): double
+toString():String Box
+calculateArea(): double
+calculatePerimeter(): double -height: double
+Box()
+Box(double,double,double)
+setHeight(double) : void
+getHeight(): double
+toString():String
+calculateVolume(): double
+calculateArea(): double
+calculatePerimeter(): double
39
Constructing Super Class and Sub Class
(Example 1)
//To declare object Rectangle in a file named
//Rectangle.java and put class Rectangle in a package
// default constructor
public Rectangle()
{
width=0;
length=0;
} 40
Constructing Super Class and Sub Class
(Example 1)
//normal constructor
public Rectangle(double width, double length)
{
this.width=width;
this.length=length;
}
//Printer
public String toString()
{
return “\nThe width:”+width+“\nThe length:”+length;
}
//Processor methods
public double calculateArea()
{
return length*width;
}
//default constructor
public Box()
{
//implicitly called super OR you can write super()
height=0;
}
43
Constructing Super Class and Sub Class
(Example 1)
//normal constructor
public Box(double width, double length, double height)
{
super(width, length);
this.height=height;
}
//Processor methods
public double calculateVolume()
{
return (getLength()*getWidth()*height);
}
45
Constructing Super Class and Sub Class
(Example 1)
public double calculateArea()
{
return ( 2*(getLength()*getWidth())+ 2*(height
*getWidth()) + 2*(getLength()*height));
}
46
Constructing Super Class and Sub Class
(Example 1)
/*To declare Java application program in a file named
TestingInheritance.java*/
import shape.*;
import java.util.*;
//input data
System.out.print("Input the width:");
double width = scanner.nextDouble();
System.out.print(“Input the lenght:");
double length = scanner.nextDouble();
System.out.print(“Input the height:");
double height = scanner.nextDouble();
47
Constructing Super Class and Sub Class
(Example 1)
//Setting the data into an object of class Box using Mutator
b.setWidth(width);
b.setLength(length);
b.setHeight(height);
System.out.println(b.toString());
System.out.println("The area :" +b.calculateArea());
System.out.println("The perimeter :"+ b.calculatePerimeter());
System.out.println("The volume :"+b.calculateVolume());
System.exit(0);
Sample of Output:
}
Input the width: 3.0
}
Input the length: 2.5
Input the height: 2.0
The width : 3.0
The length :2.5
The height : 2.0
The area : 34.0
The perimeter : 30.0
48
The volume : 15.0
Constructing Super Class and Sub Class
(Example 1)
//OR Setting the data into an object of class Box using
//normal constructor
b = new Box(width, length, height);
System.out.println(b.toString());
System.out.println("The area :" +b.calculateArea());
System.out.println("The perimeter :"+ b.calculatePerimeter());
System.out.println("The volume :"+b.calculateVolume());
System.exit(0);
Sample of Output:
}
Input the width: 3.0
}
Input the length: 2.5
Input the height: 2.0
The width : 3.0
The length :2.5
The height : 2.0
The area : 34.0
The perimeter : 30.0
The volume : 15.0
49
Constructing Super Class and Sub Class
(Example 2)
Worker
super class
-workerNum: int
-workerName: String
-position: String
+Worker()
+Worker(int, String,String) sub class
+setWorker Num(int): void
+setWorkerName(String): void
+setPosition(String): void PermanentWorker
+toString(): String
-basicSalary: double
-allowance: double
+PermanentWorker()
+PermanentWorker(int,String,String,
double, double)
+setBasicSalary(double) : void
+setAllowance(double):
50void
+calculateMonthlySalary(): double
+toString(): String
Constructing Super Class and Sub Class
(Example 2)
public class Worker
{
private int workerNum;
private String workerName;
private String position;
51
Constructing Super Class and Sub Class
(Example 2)
public void setWorkerNum(int wNum) //Setter
{
workerNum = wNum;
}
//Normal Constructor
public PermanentWorker(int wNum, String wNm, String pos, double bs, double al)
{
super(wNum, wNm, pos);
basicSalary = bs;
allowance = al;
}
56
Constructing Super Class and Sub Class
(Example 2)
//Input using normal constructor
PermanentWorker pw = new PermanentWorker(Wnum,WNm,pos,bs,a);
57
Constructing Super Class and Sub Class
(Array of Sub Class – based on Example 2)
import java.util.*;
public class AppWorker
{
public static void main(String args[])
{
Scanner scanner = new Scanner (System.in);
PermanentWorker[] pw = new PermanentWorker[10];//STEP 1: Array Declaration
60
Object of Super Class and Sub
Class
• Java allows us to treat an object of a sub class
as an object of its super class. In another
words, a reference variable of a super class
type can point to an object of its subclass.
62
Inheritance
(Type Compatibility)
Suppose we define class Undergraduate
Inherited from Student
public class Undergraduate extends Student
{
private int level;
//method members
63
Inheritance
(Type Compatibility)
• The following code is valid
Student s = new Student();
Undergraduate ug = new Undergraduate();
Person p1 = s;
Person p2 = ug;
• Even the following statements, which may look more innocent, are similarly
illegal:
Undergraduate ug = p; //ILLEGAL!
Undergraduate ug2 = s; //ILLEGAL!
65
The Operator instanceof
• To determine whether a reference variable that points
to an object is of a particular class type, Java provides
the operator instanceof.
• Example:
p instanceof Rectangle
66
The Operator instanceof
(Example 1)
TwoD
-area: double
-perimeter: double
Super class
+TwoD()
+getArea(): double
+getPerimeter(): double
+calculateArea(): void
+calculatePerimeter(): void
+toString(): String
Rectangle
//Constructor
public TwoD()
{
area=0;
perimeter=0;
}
//Getter or mutator methods
public double getArea(){return area;}
public double getPerimeter(){return perimeter;}
68
The Operator instanceof
(Example 1)
//Processor methods
public void calculateArea()
{
area = 0.0;
}
69
The Operator instanceof
(Example 1)
//Put class Rectangle in a package
package twoD;
//constructor
public Rectangle()
{
super();
width=0;
length=0;
}
70
The Operator instanceof
(Example 1)
//setter methods
public void setWidth(double w)
{
width=w;
}
//getter methods
public double getLength(){return length;}
public double getWidth(){return width;}
//processor methods
public void calculateArea()
{ 71
area=length*width;
The Operator instanceof
(Example 1)
public void calculatePerimeter()
{
perimeter=2*length+2*width;
}
//printer methods
public String toString()
{
String result;
result ="";
String line1,line2,line3,line4,line;
line = "RECTANGLE:" + "\n";
line1 = "The width : " +width+ "\n";
line2 = "The length : " +length+ "\n";
line3 = "The area : " +area+ "\n";
line4 = "The perimeter: " +perimeter+ "\n";
result = line+line1+line2+line3+line4;
return result;
} 72
}
The Operator instanceof
(Example 1)
//put class circle in a package
package twoD;
//constructor
public Circle()
{
super();
radius=0;
}
//setter methods
public void setRadius(double r)
{
radius=r;
}
73
The Operator instanceof
(Example 1)
//getter methods
public void calculateArea()
{
area=Math.PI*Math.pow(radius,2);
}
74
The Operator instanceof
(Example 1)
//printer methods
public String toString()
{
//Formating
DecimalFormat dF= new DecimalFormat("0.00");
String result;
//initialize result
result="";
String line1,line2,line3,line;
line = "CIRCLE: " + "\n";
line1 = "The width : " +radius+ "\n";
line2 = "The area : " +dF.format(area)+ "\n";
line3 = "The perimeter : " +dF.format(perimeter)+ "\n";
result = line+line1+line2+line3;
return result;
}
} 75
The Operator instanceof
(Example 1)
import twoD.TwoD;
import twoD.Rectangle;
import twoD.Circle;
import javax.swing.JOptionPane;
if(c==1)
{
Rectangle rec = new Rectangle();
//calculation
rec.calculateArea();
rec.calculatePerimeter();
78
The Operator instanceof
(Example 1)
else
{
Circle cir = new Circle();
//input number as string
String strRadius = JOptionPane.showInputDialog(
"Input the radius :");
//Calculation
cir.calculateArea();
cir.calculatePerimeter();
System.exit(0);
}
}
81
The Operator instanceof
(Example 2)
RegularService
Customer -numVoiceSms: int
-name: String
-address: String +RegularService()
-telephoneNo: String +RegularService(String,String,String,int,double,boolean, int)
-noOfSms: int +setNumVoiceSms(int): void
-minuteCall: double +getNumVoiceSms(int): int
-threeG: boolean +calcCharge(): double
+toString(): String
+Customer()
+Customer(String,String,String,int,double,boolean)
+setName(String): void
+setAddress(String): void
PremiumService
+setTelephoneNo(String): void
+setNoOfSms(int): void -minutesVideoCall: double
+setMinuteCall(double): void -minutesVideoMail: double
+setThreeG(boolean): void
+getName(): String +PremiumService()
+getAddress(String): String +PremiumService(String,String,String,int,double,boolean,
+getTelephoneNo(String): String double,double)
+getNoOfSms(int): int +setMinutesVideoCall(double): void
+getMinuteCall(double): double +setVideoMail(double): void
+getThreeG(boolean): boolean +getMinutesVideoCall(): double
+getVideoMail(): double
82
+toString(): String
+calcCharge(): double
+toString(): String
Super class
Sub class
The Operator instanceof
(Example 2)
public class Customer{
private String name;
private String address;
private String telephoneNo;
private int noOfSms;
private double minuteCall;
private boolean threeG;
//Default Constructor
public Customer()
{
name = “”;
address = “”;
telephoneNo = “”;
noOfSms = 0;
minuteCall = 0.0;
threeG = false;
}
The Operator instanceof
(Example 2)
//Normal Constructor
public Customer(String nm, String ad, String tn, int ns,
double mc, boolean tg)
{
name = nm;
address = ad;
telephoneNo = tn;
noOfSms = ns;
minuteCall = mc;
threeG = tg;
}
//Mutator
public void setName(String nm) { name = nm; }
public void setAddress(String ad) { address = ad; }
public void setTelephoneNo(String tn) {telephoneNo = tn;}
public void setNoOfSms(int ns) { noOfSms = ns; }
public void setMinuteCall(double mc) { minuteCall = mc; }
public void setThreeG(boolean tg) { threeG = tg; }
The Operator instanceof
(Example 2)
//Accessor
public String getName() { return name; }
public String getAddress() { return address; }
public String getTelephoneNo() { return telephoneNo; }
public int getNoOfSms() { return noOfSms; }
public double getMinuteCall() { return minuteCall; }
public boolean setThreeG() { return threeG; }
//Printer
public String toString()
{
return “\nName:”+name+ “\nAddress:”+address
+ “\nTelephone:”+telephoneNo+ “\nNo. of SMS:”
+noOfSms+ “\nMinute Call:”+minuteCall
+ “\nThree G:”+threeG;
}
}
The Operator instanceof
(Example 2)
public class RegularService extends Customer {
private int numVoiceSms;
//Default Constructor
public RegularService()
{
super();
numVoiceSms = 0;
}
//Normal Constructor
public RegularService(String nm, String ad, String tn,
int ns, double mc, boolean tg, int nv)
{ super(nm, ad, tn, ns, mc, tg);
numVoiceSms = nv;
}
//Mutator
public void setNumVoiceSms(int nv)
{ numVoiceSms = nv; }
The Operator instanceof
(Example 2)
//Accessor
public int getNumVoiceSms()
{ return numVoiceSms; }
//Processor
public double calcCharge()
{
double totCharge = getMinuteCall() * 0.20 +
getNoOfSms()* 0.05 + numVoiceSms*0.50;
return totCharge;
}
//Printer
public String toString()
{
return super.toString()+ “\nNum. voice SMS:” +numVoiceSms;
}
}
The Operator instanceof
(Example 2)
public class PremiumService extends Customer {
private double minutesVideoCall;
private double minutesVideoMail;
//Default Constructor
public PremiumService()
{ super();
minutesVideoCall = 0.0;
minutesVideoMail = 0.0;
}
//Normal Constructor
public PremiumService(String nm, String ad, String tn,
int ns, double mc, boolean tg, int mvc, int mvm)
{
super(nm, ad, tn, ns, mc, tg);
minutesVideoCall = mvc;
minutesVideoMail = mvm;
}
The Operator instanceof
(Example 2)
//Mutator
public void setMinutesVideoCall(double mvc)
{ minutesVideoCall = mvc; }
//Accessor
public double getMinutesVideoCall()
{ return minutesVideoCall; }
return totCharge;
}
//Printer
public String toString()
{
return super.toString()+ “\nMinutes video call:”
+minutesVideoCall+ “\nMinutes video mail:”
+minutesVideoMail;
}
}
The Operator instanceof
(Example 2)
import java.util.*;
public class CustomerApp{
public static void main(String[] args)
{
Scanner scan = new Scanner (System.in);
• Every classes that you define yourself without using inheritance are descendant
classes of the class Object. If you do not make your class a derived class of
some class, Java will automatically make it a derived class of Object.
• Example:
extends Object {
public class Employee {
data members;
method members;
}
97
The object Class
• The class Object allows Java programmers to write Java
methods that have a parameter of type Object that
represents an object of any class.
• The class Object does have some methods that every Java
class inherits