What is Inheritance?
Inheritance is a mechanism where one class acquires the properties (variables) and behaviors (methods) of another class.
Parent Class (Superclass): The class whose features are inherited.
Child Class (Subclass): The class that inherits those features.
In Java, we use the keyword extends to create this relationship.
Breakdown of Your Code
Let’s look at how your Dog class gets “superpowers” from the Animal class:
// Parent Class
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
// Child Class
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
How it works in the Main method:
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.bark(); // Own method
myDog.eat(); // Inherited method from Animal class!
}
}
Even though the Dog class does not have an eat() method written inside it, it can still use it because it “extended” the Animal class.
Why is Inheritance Important for University Students?
1. Code Reusability
Instead of writing the eat() method for Dog, Cat, Lion, and Elephant separately, you write it once in the Animal class. All other animals just inherit it.
2. “IS-A” Relationship
Inheritance represents a relationship where the child is a type of the parent.
A Dog IS-An Animal.
A Car IS-A Vehicle.
A Professor IS-A Person.
3. Method Overriding
Inheritance allows a child class to change the behavior of a parent’s method. For example, a Dog might “eat” differently than a Bird. (We will cover this in the next lesson!)
Important Rules for Exams
Single Inheritance: In Java, a class can only extend one parent class. You cannot do
class Dog extends Animal, Mammal. (This prevents confusion).Private Members: If a variable in the Parent class is
private, the Child class cannot access it directly.Object Class: In Java, every single class automatically inherits from a special class called
Object(the grandfather of all classes).
Summary Table
| Term | Meaning |
extends | The keyword used to perform inheritance. |
| Superclass | The base/parent class (e.g., Animal). |
| Subclass | The derived/child class (e.g., Dog). |
| Code Reuse | The main benefit of using inheritance. |