Review Questions

graphics/rq_icon.gif

6.9

Given the following code, which of these constructors can be added to MySubclass without causing a compile-time error?

class MySuper {
    int number;
    MySuper(int i) { number = i; }
}

class MySub extends MySuper {
    int count;
    MySub(int cnt, int num) {
        super(num);
        count=cnt;
    }

    // INSERT ADDITIONAL CONSTRUCTOR HERE
}

Select the one correct answer.

  1. MySub() {}

  2. MySub(int cnt) { count = cnt; }

  3. MySub(int cnt) { super(); count = cnt; }

  4. MySub(int cnt) { count = cnt; super(cnt); }

  5. MySub(int cnt) { this(cnt, cnt); }

  6. MySub(int cnt) { super(cnt); this(cnt, 0); }

6.10

Which statement is true?

Select the one correct answer.

  1. A super() or this() call must always be provided explicitly as the first statement in the body of a constructor.

  2. If both a subclass and its superclass do not have any declared constructors, the implicit default constructor of the subclass will call super() when run.

  3. If neither super() nor this() is declared as the first statement in the body of a constructor, then this() will implicitly be inserted as the first statement.

  4. If super() is the first statement in the body of a constructor, then this() can be declared as the second statement.

  5. Calling super() as the first statement in the body of a constructor of a subclass will always work, since all superclasses have a default constructor.

6.11

What will the following program print when run?

// Filename: MyClass.java
public class MyClass {
    public static void main(String[] args) {
        B b = new B("Test");
    }
}

class A {
    A() { this("1", "2"); }

    A(String s, String t) { this(s + t); }

    A(String s) { System.out.println(s); }
}

class B extends A {
    B(String s) { System.out.println(s); }

    B(String s, String t) { this(t + s + "3"); }

    B() { super("4"); };
}

Select the one correct answer.

  1. It will simply print Test.

  2. It will print Test followed by Test.

  3. It will print 123 followed by Test.

  4. It will print 12 followed by Test.

  5. It will print 4 followed by Test.