Inheritance allows one class to acquire the properties and methods of another class. The class that is inherited from is called the parent class or superclass, while the class that inherits is called the child class or subclass.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Dog barks"); } } public class InheritanceExample { public static void main(String[] args) { Animal myDog = new Dog(); // Creating an object of the subclass myDog.sound(); // Calls the Dog's sound method } }
In this example, the Dog
class inherits from the Animal
class. The sound()
method is overridden in the Dog
class.