Inheritance in Java allows one class to acquire the properties and behavior of another class. It promotes code reusability, method overriding, and logical class hierarchy.
extends keywordA subclass inherits a superclass using the extends keyword.
// Basic inheritance syntax
class Parent {
void show() {
System.out.println("Parent class method");
}
}
class Child extends Parent {
void display() {
System.out.println("Child class method");
}
}
// Single inheritance example in Java
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}
Animal is eating
Dog is barking
The Dog class inherits the eat() method from the Animal class.
Click the button below to see how the extends keyword unlocks capabilities.
Methods available to 'myCar':