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

Basic Inheritance Example

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.