Home / Programs / Single Inheritance in java
Programming Example

Single Inheritance in java

👁 1,506 Views
💻 Practical Program
📘 Step by Step Learning
Single Inheritance is a type of inheritance in Java where a derived class or a child class extends a single base class or a parent class. This means that the child class inherits all the properties and methods of the parent class, including the public and protected fields and methods. Single inheritance creates a parent-child relationship between two classes, where the child class is a specialized version of the parent class. In Java, single inheritance is supported through the "extends" keyword.

Program Code

 class AnimalClass{
void eat(){System.out.println("eating...");}
}

class Dog extends AnimalClass{
void bark(){System.out.println("barking...");}
}

class InheritanceClass{
	public static void main(String args[]){
	Dog obj=new Dog();
	obj.bark();
	obj.eat();
  }
}

Output

barking...
eating...
Press any key to continue . . .

Explanation

This code demonstrates single inheritance in Java. The AnimalClass is a base class that has a method named eat(). The Dog class extends the AnimalClass and has an additional method called bark(). The InheritanceClass contains the main method and creates an object of Dog class to access its methods.

When the program runs, it creates an object of the Dog class and calls the bark() method, which prints "barking..." to the console. It then calls the eat() method, which is inherited from the AnimalClass and prints "eating..." to the console. This demonstrates how the Dog class inherits the behavior of the AnimalClass and extends it with its own behavior.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.