Inheritance is one of the core concepts of Object-Oriented Programming (OOP) in Java that allows one class to acquire the properties and behaviors of another class. It promotes code reusability by enabling a child class to inherit fields and methods from a parent class.
Key Points: • Inheritance allows a class to reuse the code of an existing class. • The class being inherited from is called the parent class (superclass), and the inheriting class is called the child class (subclass). • It helps reduce code duplication and improves maintainability. • Java uses the extends keyword to implement inheritance. • Inheritance supports method overriding, enabling a child class to provide its own implementation of a parent class method. • It establishes an "is-a" relationship between classes.
Example: A Dog is an Animal. Instead of writing common properties and behaviors again, the Dog class can inherit them from the Animal class.
Code Example:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class Demo {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}Output:
Animal is eating Dog is barking
Benefits of Inheritance:
• Code reusability • Reduced code duplication • Easier maintenance • Supports method overriding • Establishes hierarchical relationships between classes
Interview Tip: A concise interview answer is:
"Inheritance is an OOP feature that allows one class to acquire the properties and methods of another class. It promotes code reuse, reduces duplication, and helps establish an 'is-a' relationship between parent and child classes using the extends keyword."