Inheritance is the most popular feature of object oriented programming(OOPs).
It means reusability of code.In Software engeneering , reusability is the use of existing code in some form within the software product development process.
In java, inheritance allow the programmer to use the code of one class into another class through the concept or relation of parent and child. The child can use the resources or code of parent class by acquiring its methods ,behaviors, data members and also add their own methods and data member by the help of inheritance.
The child class is also known as sub -class and Parent class also called as Super-class or base class.
Inheritance represents the parent-child relationship, also known as IS-A relationship.
Uses Of Inheritance
1) Code reusability
2) Saves time in program development.
3) Method Overriding(Run time Polymorphism) know more about it later in tutorials.
Syntax Of Inheritance
class Subclass-name extends Parentclass-name
{
//methods and fields
}
How To Use Inheritance?
class Dog extends Animal
{
//methods and fields
}
extends The extends is keyword that are use to extend or show that , the child class acquired or inherit the base or parent class.
Example Of Inheritance
package com.example.SpringBootSecurity.controllers;
class Animal {
public Animal() {
System.out.println("Animal has been created");
}
public void sleep() {
System.out.println("Animal Sleeping");
}
public void eat() {
System.out.println("Animal Eating");
}
}
public class Bird extends Animal {
public Bird() {
super();
System.out.println("Bird has been created");
}
@Override
public void sleep() {
System.out.println("Bird Sleeping");
}
@Override
public void eat() {
System.out.println("Bird Eating");
}
public static void main(String[] args) {
Animal animalObj = new Animal();
Bird birdObj = new Bird();
animalObj.sleep();
animalObj.eat();
birdObj.sleep();
birdObj.eat();
}
}
Output
Animal has been created
Animal has been created
Bird has been created
Animal Sleeping
Animal Eating
Bird Sleeping
Bird Eating
Example Of Hierarchical Inheritance
class Engine {
void show() {
System.out.println("This is engine");
}
}
class Car extends Engine {
void display() {
System.out.println("This is car");
}
}
class Truck extends Engine {
void display() {
System.out.println("This is truck");
}
}
public class HierarchicalInheritance {
public static void main(String[] args) {
Car car = new Car();
car.show();
car.display();
Truck truck = new Truck();
truck.show();
truck.display();
}
}
Output
This is engine
This is car
This is engine
This is truck