AP Computer Science A · Topic 9.2
Writing Constructors for Subclasses Practice
Part of Inheritance.
Practice questions
19
Sample questions
5 of 19 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 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
- Ccheck_circle
Rex
- D
Compile error: Dog has no getName
Why
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".
- A
Sample 2difficulty 2/5
public class A { public A() { System.out.print("A "); } } public class B extends A { public B() { System.out.print("B "); } } new B();What is printed when <code>new B()</code> runs?
- Acheck_circle
A B
- B
B A
- C
B
- D
A
Why
Every subclass constructor implicitly calls <code>super()</code> first. So <code>A()</code> runs, printing "A ", then <code>B()</code> prints "B ".
- A
Sample 3difficulty 2/5
public class Base { public Base() { System.out.print("B "); } } public class Child extends Base { public Child() { System.out.print("C "); } } // ... new Child();What is printed?
- A
B
- B
C
- C
C B
- Dcheck_circle
B C
Why
Java implicitly calls super() before the body of the subclass constructor, so Base prints first.
- A
Sample 4difficulty 2/5
public class Person { private String name; public Person(String n) { name = n; } public String getName() { return name; } } public class Student extends Person { private int id; public Student(String n, int i) { super(n); id = i; } } // Usage: Student s = new Student("Maya", 7); System.out.print(s.getName());What is printed?
- A
Compile error
- B
null
- C
7
- Dcheck_circle
Maya
Why
super("Maya") sets name in Person. getName returns "Maya".
- A
Sample 5difficulty 3/5
public class A { protected int x; public A() { x = 1; } public A(int v) { x = v; } } public class B extends A { public B() { super(5); } } // Usage: B b = new B(); System.out.print(b.x);What is printed?
- Acheck_circle
5
- B
1
- C
Compile error
- D
0
Why
super(5) calls A's parameterized constructor, setting x to 5.
- A