🎯 What you will learn
- Extend a parent class
- Override methods with @Override
- Use polymorphism with a parent type
👋 Let’s get started!
A Cat IS AN Animal. A Dog IS AN Animal. Inheritance lets child classes reuse a parent’s code 🧬, and polymorphism lets one line of code work for many kinds of objects.
🪜 Step by step
1. 👪 extends
The child gets the parent’s fields and methods.
class Animal {
String name;
void eat() { System.out.println(name + " eats"); }
}
class Dog extends Animal {
void fetch() { System.out.println(name + " fetches!"); }
}
2. 🔁 @Override
Children can replace a parent method with their own version.
class Animal {
String sound() { return "..."; }
}
class Cat extends Animal {
@Override
String sound() { return "Meow"; }
}
3. 🎭 Polymorphism
A parent-type variable can hold any child — and the child’s method runs.
Animal[] zoo = { new Cat(), new Dog() };
for (Animal a : zoo) {
System.out.println(a.sound());
}
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
Shape family
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Square extends Shape {
double s;
Square(double s) { this.s = s; }
double area() { return s * s; }
}
// main:
Shape[] shapes = { new Circle(1), new Square(3) };
for (Shape sh : shapes) {
System.out.printf("%.2f%n", sh.area());
}Override a method
class Bird extends Animal {
@Override
String sound() {
return "Tweet";
}
}📖 Key words
Tap a card to flip it over!
- Inheritance
- A child class reusing a parent class 🧬
- extends
- Makes a class a child of another 👪
- @Override
- Replaces a parent method 🔁
- Polymorphism
- One interface, many forms 🎭
🏆 Challenge
Predict the output.
Challenge
class Vehicle { String wheels() { return "some"; } }
class Bike extends Vehicle { String wheels() { return "2"; } }
class Car extends Vehicle { String wheels() { return "4"; } }
// main:
Vehicle v = new Car();
System.out.println(v.wheels());Knowledge Check Quiz
- What does extends do?
- What prints?
- A Cat “is a” …