Home Java Programming Language / Programs / Single Inheritance in java
🚀 Programming Example

Single Inheritance in java

👁 1,510 Views
💻 Practical Program
📘 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();
  }
}
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.