Writing Constructors for Subclasses

AP Computer Science A· difficulty 2/5

public class Animal {
    private String name;
    public Animal(String n) { name = n; }
    public String getName() { return name; }
}
public class Dog extends Animal {
    private String breed;
    public Dog(String n, String b) {
        super(n);
        breed = b;
    }
}
// Usage:
Dog d = new Dog("Rex", "Lab");
System.out.print(d.getName());

What is printed?

  • A

    Lab

  • B

    RexLab

  • C

    Rex

    check_circle
  • D

    Compile error: Dog has no getName

Explanation

Dog inherits getName() from Animal. The super(n) call passes "Rex" to Animal's constructor, which assigns it to name. Calling d.getName() returns "Rex".

Want 10 more like this — adaptive to your weak spots?

Related questions