Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

7.1 Inheritance — extends and inherited methods

Lesson

Building one class on another

A class can build on an existing class with the keyword extends. The new class — the subclass — automatically inherits the fields and methods of the original — the superclass. This models an is-a relationship: since Dog extends Animal, a Dog is an Animal, so it already has everything Animal can do.


Worked example

class Animal {
    public String describe() { return name + " is an animal"; }
}
class Dog extends Animal {   // Dog is-an Animal
    public Dog(String name) { super(name); }
}

Dog d = new Dog("Rex");
System.out.println(d.describe());   // "Rex is an animal" — inherited!

Dog never defines describe(), yet d.describe() works — it is inherited from Animal.


▶ Try it: run this — the Dog object can call describe() and getName(), both defined in Animal.



class Dog extends Animal means Dog...


'Dog extends Animal' expresses that...


Type exactly what this program prints.

class Animal { String n; Animal(String x){n=x;} String describe(){return n+" is an animal";} }
class Dog extends Animal { Dog(String x){super(x);} }
public class Main { public static void main(String[] a){
    System.out.println(new Dog("Sam").describe());
}}

Match each term to its meaning.


True or false?