TL ; DR:
A child class can inherit from a parent class — it gets all the parent's fields and methods for free, and can add its own. This lets you reuse code instead of copy-pasting it.
class Puppy extends Dog {
public Puppy(String name) { super(name); }
def whine() { println("whimper"); }
}
Full lesson:
Inheritance is one of the four classic OOP pillars (along with encapsulation, polymorphism, and abstraction). The idea is simple: most real-world things are kinds of other things — a Puppy is a Dog, a Car is a Vehicle, a Manager is an Employee. When you model that "is-a" relationship in code, the child class gets the parent's data and behavior automatically.
What gets inherited?
- Fields — the Puppy has a
namefield even though we only declared it on Dog. - Methods — the Puppy can call
bark()even though we only defined it on Dog. - The contract — anywhere code expects a Dog, you can pass a Puppy (we'll see this when we cover polymorphism).
What you still write
- The constructor usually has to forward arguments up to the parent's constructor (because the parent's fields need initializing).
- Any new methods or new fields specific to the child.
Your task
Below the Dog class, create a Puppy class that inherits from Dog and adds one new method, whine(), that prints "whimper". The harness creates a Puppy named "Buddy", calls its inherited bark(), and then its new whine().
Expected output:
Woof! I am Buddy
whimperFree plan: 30 tutor messages. Premium is unlimited.