Inheritance in Java allows a class to inherit properties and behaviors (methods) from another class. The class that inherits is called a subclass, and the class being inherited from is called a superclass.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { void sound() { System.out.println("Woof"); } } public class InheritanceExample { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); // Calls the overridden method } }
The Dog
class inherits from the Animal
class. It overrides the sound()
method to provide its own implementation.
class Animal { Animal() { System.out.println("Animal created"); } } class Dog extends Animal { Dog() { super(); // Calling superclass constructor System.out.println("Dog created"); } } public class public class InheritanceExample { public static void main(String[] args) { Dog dog = new Dog(); // Calls the constructor of Animal and Dog } }
In this example, the Dog
class calls the constructor of the superclass Animal
using the super()
keyword before executing its own constructor.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Woof"); } } public class InheritanceExample { public static void main(String[] args) { Animal animal = new Dog(); // Polymorphism animal.sound(); // Calls the overridden method in Dog } }
Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. The @Override
annotation indicates that a method is overriding a superclass method.