You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Inheritance lets you create new classes based on existing ones, reusing and extending their behaviour. Polymorphism means a single interface can represent different underlying forms. Together, they are two of the four pillars of object-oriented programming.
extendsA subclass (child) inherits fields and methods from a superclass (parent):
public class Animal {
String name;
public Animal(String name) {
this.name = name;
}
public void speak() {
System.out.println(name + " makes a sound");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // call the parent constructor
}
@Override
public void speak() {
System.out.println(name + " barks");
}
}
| Rule | Detail |
|---|---|
| Single inheritance only | A class can extend exactly one parent class |
super() | Calls the parent constructor — must be the first statement |
@Override | Annotation indicating a method overrides a parent method |
All classes extend Object | If no extends is specified, the class implicitly extends java.lang.Object |
super Keyword| Use | Example |
|---|---|
| Call parent constructor | super(name); |
| Call parent method | super.speak(); |
| Access parent field | super.field (if not private) |
@Override
public void speak() {
super.speak(); // call Animal's speak()
System.out.println(name + " also barks loudly!");
}
Polymorphism means "many forms". A parent reference can hold a child object:
Animal myAnimal = new Dog("Rex");
myAnimal.speak(); // "Rex barks" — the Dog version is called
This is called runtime polymorphism (dynamic dispatch) — the actual method called depends on the object's real type, not the reference type.
Animal[] animals = {
new Dog("Rex"),
new Cat("Whiskers"),
new Bird("Tweety")
};
for (Animal a : animals) {
a.speak(); // each calls its own version of speak()
}
An abstract class cannot be instantiated directly. It may contain abstract methods (without a body) that subclasses must implement:
public abstract class Shape {
String colour;
public Shape(String colour) {
this.colour = colour;
}
// Abstract method — no body
public abstract double area();
// Concrete method — has a body
public void describe() {
System.out.println("A " + colour + " shape with area " + area());
}
}
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.