0% found this document useful (0 votes)
2 views36 pages

W6. Inheritance

The document provides an overview of inheritance in Object Oriented Programming, explaining key concepts such as superclass, subclass, and the use of the 'super' keyword. It outlines the types of inheritance in Java, including single, multilevel, and hierarchical inheritance, and discusses method overriding. Additionally, it includes examples and diagrams to illustrate how inheritance works in practice.

Uploaded by

iqra.68412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views36 pages

W6. Inheritance

The document provides an overview of inheritance in Object Oriented Programming, explaining key concepts such as superclass, subclass, and the use of the 'super' keyword. It outlines the types of inheritance in Java, including single, multilevel, and hierarchical inheritance, and discusses method overriding. Additionally, it includes examples and diagrams to illustrate how inheritance works in practice.

Uploaded by

iqra.68412
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Object Oriented Programming

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

Abstraction inheritance Polymorphism Encapsulation

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.

• Therefore, a subclass is a specialized version of a superclass. It inherits all


of the variables and methods defined by the superclass and adds its own,
unique elements.

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:

• A hierarchy of inheritance can be created in which a subclass becomes a


superclass of another subclass.
• Only one superclass can be specified for any subclass.

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.

When a subclass inherits more than one


class it is called Multiple Inheritance. In
java programming, multiple inheritance is
supported through interface only.

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

class BoxWeight extends Box


{
double weight; // weight of box
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " +
mybox1.weight);
}
}

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

– we often don't draw trivial / obvious


generalization relationships, such as drawing
the Object class as a parent

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:

• Here, arg-list specifies any arguments needed by the constructor in the


superclass.
• super( ) must always be the first statement executed inside a subclass’
constructor.
• super( ) always refers to the superclass immediately above the calling
class. This is true even in a multileveled hierarchy.

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:

• Member can be either a method or an instance variable.


• This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in the
superclass.

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.

For example, given three classes called A, B, and C,


C can be a subclass of B, which is a subclass of A.
C inherits all aspects of B and A.

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!

A superclass has no knowledge of any subclass, any initialization it needs to


perform is separate from and possibly prerequisite to any initialization
performed by the subclass. Therefore, it must be executed first.

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

Abstraction inheritance Polymorphism Encapsulation

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

You might also like