w1coding.comAll tutorials

Java Inheritance

Java lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Control
  5. Loops
  6. Arrays
  7. Methods
  8. OOP
  9. Contractors
  10. Inheritance
  11. Polymorphism
  12. Abtract
  13. Interfaces
  14. Constructors
  15. Static
  16. Exception
  17. Collections
  18. Lambda
  19. Streams
  20. Strings
  21. Date
  22. Interface
  23. Inheritance
  24. Polymorphism
  25. Exception
  26. File

Java Inheritance

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.

Basic Inheritance Example

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.

Constructor in Inheritance

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.

Method Overriding

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.