Chapter 02 Inheritance
Chapter 02 Inheritance
PROGRAMMING
CS 1032
Chapter – 02
Inheritance
2
Principles of OOP
Pillars of OOP
All object-oriented programming
languages provide mechanisms that
helps you implement the object
Encapsulation
Polymorphism
Abstraction
Inheritance
oriented model.
Class 3
Object
Inheritance
• Inheritance is a key feature in OOP that provides a
mechanism to inherit property of one class by another
class.
• Create new classes that are built upon existing classes.
Methods and fields of parent class, can be reuse by
inherit from an existing class, and new methods and
fields also can be add.
• Inheritance represents the IS-A relationship, also
known as parent-child relationship.
4
Inheritance
5
Super-classes and Sub-classes
• A class that is derived from another class is called a subclass (also a derived class,
extended class, or child class).
• The class from which the subclass is derived is called a super class (also a base class
or a parent class).
• A class which is a subtype of a more general class is said to be inherited from it.
• The sub-class inherits the base class’ data members and member functions.
Syntax:
class Subclass-name extends Superclass-name {
//methods and fields
}
6
Terminologies
subclass super-class
or or
extends
derived class base class
9
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
Class B Class B
Class B Class C
Class C
10
super keyword
• The keyword super refers to the super class and can be used to invoke the
super class's methods and constructors.
11
//example without super keyword
class Vehicle{ //example of super keyword
Example
int speed=50; class Vehicle{
} int speed=50;
class Bike3 extends Vehicle{ }
int speed=100; class Bike4 extends Vehicle{
void display(){ int speed=100;
System.out.println(speed); void display(){
//will print speed of Bike System.out.println(super.speed);
} //will print speed of Vehicle now
public static void main(String args[]){ }
Bike3 b=new Bike3(); public static void main(String args[]){
b.display(); Bike4 b=new Bike4();
} b.display();
} 12
}
Output: 100
} Output: 50
class Vehicle{ Example:
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){ Output:
super();//will invoke parent class constructor Vehicle is created
System.out.println("Bike is created"); Bike is created
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
} 13
class Person{
void message(){System.out.println("welcome");}
Example
}
class Student extends Person{
Output:
void message(){System.out.println("welcome to java");}
welcome to java
void display(){ welcome
message(); //current class message() method
super.message();
//parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
14
}
}
Exercise
15
Chapter 03
16