Saturday, August 28, 2010

No-argument constructor

Courtesy of Sun Web Learning Center



Given:

2. class Cat {
3.   Cat(int c) { System.out.print("cat" + c + " "); }
4. }
5. class SubCat extends Cat {
6.   SubCat(int c) { super(5); System.out.print("cable "); }
7.   SubCat() { this(4); }
8.   public static void main(String [] args) {
9.     SubCat s = new SubCat();
10.   }
11. }

What is the result?


A cat5
B cable
C cable cat5
D cat5 cable
E Compilation fails.
F An exception is thrown at runtime.

D is correct. Type Cat does NOT need a no-argument constructer because SubCat's no-argument constructor calls SubCat's one argument constructor.

No comments:

Post a Comment