← Learning Hub
Beginner

Inheritance and Polymorphism

Inheritance lets a class reuse another class with extends. The child gets the parent's fields and methods and can add or change them.

Polymorphism means one call can behave differently depending on the real object. A child changes a method with @Override.

Inheritance models an "is a" relationship: a CardPayment is a Payment, a Car is a Vehicle. The common code lives once in the parent; each child adds only what makes it different. This avoids copying the same code into many classes.

Polymorphism is the powerful part. You can keep a list of Payment objects - some card, some UPI, some cash - and call fee() on each. Java automatically runs the right version for each real object. Adding a new payment type later doesn't require changing the code that uses payments. @Override asks the compiler to check that you're really replacing a parent method (and not making a typo).

Example
You can edit this code.

Abstract classes

An abstract class cannot be created directly. It can have abstract methods with no body that every child must write.

Use an abstract class when several classes share some code but the parent idea is too general to exist on its own - nobody creates a plain "Shape", only circles and rectangles. The abstract method forces every child to provide its own version.

Example
abstract class Shape {
    abstract double area();
}

class Square extends Shape {
    double side = 4;
    double area() { return side * side; }
}
A Java class can extend only one class. Use super.method() to call the parent's version.
Key points
  • extends creates a child class that reuses the parent.
  • @Override replaces a parent method in the child.
  • Polymorphism: the same call runs the right version for each object.
  • Abstract classes can't be created directly and force children to fill in methods.

📝 Test yourself

1. Which keyword makes one class inherit from another?
2. How many classes can a Java class extend?
3. Fill in the annotation used when changing a parent method:
@