Today I came by 9.10. Today I learned what is Inheritance.Inheritance in Java is the mechanism by which one class can acquire the properties (fields) and behaviors (methods) of another class.
The parent class (superclass)
The child class (subclass)
In Java, inheritance is achieved using the extends keyword.
Syntax of Inheritance
class Parent {
// parent fields and methods
}
class Child extends Parent {
// child fields and methods
}
Types of Inheritance in Java
*Single Inheritance
*Multi level Inheritance
*Hierarchical Inheritance
*Multiple Inheritance
*Hybrid Inheritance
**Single Inheritance**
Single inheritance means a class inherits from only one parent class
For example program:
class Animal {
void eat()
{
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void barks()
{
System.out.println("Dog is barking");
}
}
public class Single {
public static void main(String[] args) {
Dog d1 = new Dog ();
d1.eat();
d1.barks();
}
}
Output:
Animal is eating
Dog is barking
Multilevel Inheritance
A chain of inheritance (principal → Teacher → student)
For example program:
class Principal {
void duty() {
System.out.println("Principal manages the school.");
}
}
class Teacher extends Principal {
void teach() {
System.out.println("Teacher teaches students.");
}
}
class Student extends Teacher {
void learn() {
System.out.println("Student learns from the teacher.");
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.duty();
s.teach();
s.learn();
}
}
Output:
Principal manages the school
Teacher teaches the students
Student learns from the teacher
Hierarchical Inheritance
Multiple classes inherit from the same parent class.
For example program:
class Car {
void car() {
System.out.println("This is a car");
}
}
class Brand extends Car {
void Brand() {
System.out.println("Brand: BMW");
}
}
class FuelType extends Car {
void Fuel() {
System.out.println("Fuel Type: Petrol");
}
}
public class Hierarchical {
public static void main(String[] args) {
Brand b = new Brand();
b.car();
b.Brand();
FuelType f = new FuelType();
f.car();
f.Fuel();
}
}
Output:
This is a car
Brand: BMW
This is a car
Fuel Type: Petrol
Top comments (0)