Below is a complete example of single inheritance in Java, including the code and the expected output.

Example Code

				
					// Superclass
class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

// Subclass
class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

// Main class to test the inheritance
public class SingleInheritanceTest {
    public static void main(String[] args) {
        Dog myDog = new Dog();
        myDog.eat();  // Inherited method from Animal class
        myDog.bark(); // Method from Dog class
    }
}

				
			

Explanation

  • Superclass’ Animal:

    • It has a method ‘eat()‘ that prints “This animal eats food.”.
  • Subclass ‘Dog:

    • It inherits from ‘Animal'.
    • It has an additional method ‘bark()‘ that prints “The dog barks.”.
  • Main Class ‘SingleInheritanceTest:

    • It creates an instance of ‘Dog‘.
    • It calls the inherited ‘eat()‘ method and the ‘bark()‘ method from the ‘Dog‘ class.

Expected Output

				
					This animal eats food.
The dog barks.

				
			

Detailed Explanation of Output

  • When myDog.eat() is called, it executes the eat() method defined in the Animal class, producing the output “This animal eats food.”.
  • When myDog.bark() is called, it executes the bark() method defined in the Dog class, producing the output “The dog barks.”.

This simple example demonstrates how single inheritance allows the Dog class to inherit behavior from the Animal class and extend it with additional functionality.

Scroll to Top