W6. Inheritance
W6. Inheritance
Inheritance
Prepared By
Mehak Usmani
1
Objectives
1. To understand the Inheritance relationship
2. To understand Superclass & subclass
3. To learn the Super keyword and its usage
4. To understand & implement Multilevel Hierarchy
5. To understand Constructors’ calling sequence in inheritance
6. To understand concept of Method Overriding
2
Inheritance
OOP
3
Inheritance
• Inheritance is one of the four pillars of object-oriented programming
because it allows the creation of hierarchical classifications.
• Using inheritance, a general class can be created that defines traits
common to a set of related items. This class can then be inherited by
other, more specific classes, each adding those things that are unique to
it.
• In the terminology of Java;
– A class that is inherited is called a superclass.
– The class that does the inheriting is called a subclass.
4
Basics
• To inherit a class, simply incorporate the definition of one class into
another by using the extends keyword.
• The general form of a class declaration that inherits a superclass is shown
here:
5
Example
In the example below, Shape is a superclass and Circle, Square and Triangle all
are subclasses of Shape.
6
Types of inheritance
There can be three types of inheritance in java:
1. Single,
2. Multilevel
3. Hierarchical.
7
Applying Inheritance
• To inherit a class, simply incorporate the definition of one class into
another by using the extends keyword.
8
9
Output
10
Member Access and Inheritance
• A subclass includes all of the members of its superclass, it cannot access
those members of the superclass that have been declared as private.
11
Example Box class
class Box {
double width;
double height;
double depth;
Box(){}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
12
Example Box class
13
Representing Inheritance in Class diagram
• Generalization (inheritance) relationships
– hierarchies drawn top-down with arrows
pointing upward to parent
– line/arrow styles differ, based on whether
parent is a(n):
• class:
solid line, black arrow
• abstract class:
solid line, white arrow
14
Representing Inheritance in Class diagram
UML permits a class to inherit from multiple superclasses, although some
programming languages (e.g., Java) do not permit multiple inheritance.
Student Employee
TeachingAssistant
Superclass Variable referencing Subclass Object
• A reference variable of a superclass can be assigned a reference to any
subclass derived from that superclass.
• When a reference to a subclass object is assigned to a superclass
reference variable, it will have access to only those parts of the object
that is defined by the superclass.
Error
16
Using super
• When the constructor for subclass explicitly initializes the instance
variables of its superclass, we repeat the same code found in its
superclass, which is inefficient and it implies that a subclass must be
granted access to these members.
• There are cases when a superclass keeps the details of its implementation
to itself, implementing encapsulation.
• Whenever a subclass needs to refer to its immediate superclass, it can do
so by use of the keyword super.
17
Using super
• super has two general forms.
• It can be used to
1. call the superclass’ constructor.
2. access a member of the superclass that has been hidden.
18
Using super to Call Superclass Constructors
• A subclass can call a constructor defined by its superclass by use of the
following form of super:
19
Using super to Call Superclass Constructors
20
Using super to access members of Superclass
• The second form of super acts somewhat like this, except that it always
refers to the superclass of the subclass in which it is used.
• This usage has the following general form:
21
Example
22
Practice!
Write a java Program considering the following scenario.
• Mobile is an Object that contains basic functionalities including Calling & Receiving
a call & Messaging. The Mobile has certain features including Processor, internal
memory, single or dual SIM, weight. The IMEI number is only used for identifying
the device.
• There can be different mobiles like Samsung, iPhone or Nokia which have their
own features along with the basic functionality of a mobile phone.
• In case of Samsung, the Android version, Camera Specs and playing FM Radio,
capturing photos.
• iPhone may have an ios version, Music Player, Camera.
• Any of these mobile phones can be used to make a call or send a text message.
23
Creating a Multilevel Hierarchy
• Class hierarchies can be built that contain many layers of inheritance.
• In Java it is perfectly acceptable to use a subclass as a superclass of
another.
24
class Box { // Add shipping costs.
private double width; class Shipment extends BoxWeight {
private double height; double cost;
Shipment(int i, int j, int k, int l,
private double depth;
int m) {
super(i,j,k,l);
// compute and return cost = m; }
volume }
double volume() {
return width * height * class DemoShipment {
depth; public static void main(String
} args[]) {
Shipment shipment1 = new
class BoxWeight extends Box Shipment(10, 20, 15, 10, 3.41);
{ double vol = shipment1.volume();
System.out.println("Volume is " +
double weight; // weight of
vol);
box
System.out.println("Weight is " +
. shipment1.weight);
. }
} }
25
When Constructors Are Called!
• When a class hierarchy is created, in what order are the constructors for
the classes that make up the hierarchy called?
ClassA() {}
ClassC obj= new ClassC();
ClassB() {}
ClassC() {}
26
When Constructors Are Called!
• In a class hierarchy, constructors are called in order of derivation, from
superclass to subclass.
• Further, since super( ) must be the first statement executed in a subclass’
constructor, this order is the same whether or not super( ) is used.
• If super( ) is not used, then the parameter-less constructor of each
superclass will be executed.
27
When Constructors Are Called!
class A { class C extends B {
A() { C() {
System.out.println System.out.println
("Inside C's constructor.");
("Inside A's
}
constructor.");
}
}
} class CallingCons {
class B extends A { public static void main(String
B() { args[]) {
System.out.println C objectC = new C();
}
("Inside B's
}
constructor.");
}
}
28
When Constructors Are Called!
29
Constructor Chaining
• Constructor Chaining is nothing but calling one Constructor from another.
• We can use this keyword and super keyword in calling a constructor.
• this can be used to call a constructor within the same class.
• super can be used to call the constructor of the Parent class
• if you didn’t call the Parent class Constructor then the compiler will
be automatically calling the Parent class no-args constructor by itself.
30
Method Overriding
OOP
Overloading Overriding
31
Method Overriding
• In a class hierarchy, when a method in a subclass has the same name and
type signature as a method in its superclass, then the method in the
subclass is said to override the method in the superclass.
• When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of
the method defined by the superclass will be hidden.
• In order to access the superclass version of an overridden method, super
can be used.
32
Method Overriding
class Parent
{ void show(){
System.out.println("Parent called");
}
}
class Child extends Parent
{ void show(){
System.out.println("Child called");
}
}
Output:
Child c = new Child(); Child called
c.show();
33
Method Overriding
class Parent
{ void show(){
System.out.println("Parent called");
}
}
class Child extends Parent
{ void show(){
super.show();
System.out.println("Child called");
}
Output:
} Parent called
Child c = new Child(); Child called
c.show();
34
Method Overriding
• Method overriding occurs only when the names and the type signatures
of the two methods are identical. If they are not, then the two methods
are simply overloaded.
35
Method Overriding
class Parent
{ void show(){
System.out.println("Parent called");
}
}
class Child extends Parent
{ void show (String msg){
System.out.println(msg);
}
} Output:
Child c = new Child(); Parent called
c.show(); Overloading
c.show(“Overloading”);
36