Inheritance is a core concept of Object-Oriented Programming in Java. It allows one class to acquire the properties and methods of another class, promoting code reusability and hierarchical relationships.
extends keywordA child class (subclass) inherits from a parent class (superclass). The subclass can use existing methods and also define new behavior.
// Parent class definition
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Child class inheriting Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
// Main class to test inheritance
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
d.bark();
}
}
Animal makes a sound
Dog barks
The Dog class automatically gets access to the sound() method from the Animal class due to inheritance.
Create Object: SportsCar s = new SportsCar();
Vehicle class and inherit it in a Car class