You are on page 1of 14

Topic-1

Inheritance-Super classes-Sub class


Inheritance

Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class,
parent class).

extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Inheritance

Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Types of Inheritance in Java

1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance (Not supported in Java)
4. Hierarchical Inheritance
5. Hybrid Inheritance
Inheritance
Inheritance
Inheritance
Example for Single Inheritance
class Teacher {
Teacher
String designation = "Teacher";
(Super Class)
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher{


String mainSubject = "Physics"; Physics Teacher
public static void main(String args[]){ (Sub Class)
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Inheritance

The base class is Teacher and it is inherited by class Physics Teacher. The methods and
variables of class Teacher can be accessed by object of class Physics Teacher, because we
applied inheritance. So create an object for sub class instead of super class.
Inheritance
Example for Multilevel Inheritance

class Teacher { Teacher


String designation1 = "Physics Teacher"; (Super Class)
String designation2 = "Chemistry Teacher";
String collegeName = "VelTechMultiTech";
void does(){
System.out.println("Teaching");
}
} Physics Teacher
(Sub Class of Teacher)
class PhysicsTeacher extends Teacher{ (Super class of Chemistry
void teaching() Teacher)
{
System.out.println("Teaching Physics");
}
}
Chemistry Teacher
(Sub Class)
Inheritance
Example for Multilevel Inheritance

class ChemistryTeacher extends PhysicsTeacher


{
public static void main(String args[]){
ChemistryTeacher obj = new ChemistryTeacher();
System.out.println(obj.collegeName);
obj.does();
System.out.print(obj.designation1+"- ");
obj.teaching();
}
}

The above program is example of multilevel inheritance in java. The class Teacher is
inherited by class Physics Teacher. In turn the class Physics Teacher is inherited by class
Chemistry Teacher. The inheritance contain more than one level, since it is called multilevel
inheritance.

You might also like