Task 5 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 — adding to a subclass

Lesson

Inherited plus new

A subclass is not limited to what it inherits — it adds its own fields and methods too. And its new methods can use the inherited ones. So a subclass is: everything inherited from the superclass, plus whatever new members you give it.


Worked example

class Dog extends Animal {
    public Dog(String name) { super(name); }
    public String fetch() {
        return getName() + " fetches the ball";   // uses inherited getName()
    }
}

fetch() is Dog's own method, and inside it calls the inherited getName().


▶ Try it: run this — describe() is inherited and fetch() is Dog's own; both work on the same object.



A subclass can...


A subclass's own method can...


Type exactly what this program prints.

class Animal { String n; Animal(String x){n=x;} String getName(){return n;} }
class Dog extends Animal { Dog(String x){super(x);} String fetch(){return getName()+" fetches";} }
public class Main { public static void main(String[] a){
    System.out.println(new Dog("Rex").fetch());
}}

In Dog, fetch() calls getName(), which is...


True or false?