CoreJavaTutorials
Contribute Us | Ask Question |

Inheritance in Java

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

 class Animal {
	public Animal() {
		System.out.println("A new animal has been created!");
	}
	
	public void sleep() {
		System.out.println("An animal sleeps...");
	}
	
	public void eat() {
		System.out.println("An animal eats...");
	}
}

 class Bird extends Animal // Bird class inherit the Animal class
{
	public Bird() {
		super();
		System.out.println("A new bird has been created!");
	}
	
	@Override
	public void sleep() {
		System.out.println("A bird sleeps...");
	}
	
	@Override
	public void eat() {
		System.out.println("A bird eats...");
	}
public static void main(String[] args) {
		Animal animal = new Animal();
		Bird bird = new Bird();
		
		
	animal.sleep();
		animal.eat();
		
		bird.sleep();
		bird.eat();
}
}

		

way for compile and run program

javac Bird.java
java Bird

Output:

example 1
		

Example of Hierarchical Inheritance

class Food{

 void show(){
System.out.println("food");
}
}
class Adult extends Food{

void display(){
System.out.println("eat food");
}
}
class Baby extends Food{

void drink(){
System.out.println("drink milk");
}
}
class Test
{

public static void main(String[] args)
{
Adult adult=new Adult();
adult.show();
adult.display();
Baby b=new Baby();
b.show();

b.drink();
}
}

way for compile and run program

javac Test.java
java Test

Output:

food
eat food
food
drink milk