2009年2月4日 星期三

第18題SampleCode

Given:
1. class Super{
2. private int a;
3. protected Super(int a){this.a = a;}
4. }
...
11. class Sub extends Super{
12. public Sub(int a){super(a);}
13. public Sub(){this.a = 5;}
14. }

Which two, independently, will allow Sub to compile? (Choose two.)
A. Change line 2 to:public int a;
B. Change line 2 to:protected int a;
C. Change line 13 to:public Sub(){this(5);}
D. Change line 13 to:public Sub(){super(5);}
E. Change line 13 to:public Sub(){super(a);}

答案:CD
參考:6-5 繼承

---------------------------------------------------------------
class Super{
private int a;
// public int a;
// protected int a;
protected Super(int a){this.a = a;}
}

class Sub extends Super{
public Sub(int a){super(a);}

// public Sub(){this(5);}
// public Sub(){super(5);}
// public Sub(){super(a);} //Cannot refer to an instance field a while explicitly invoking a constructor
public Sub(){this.a = 5;} //Implicit super constructor Super() is undefined. Must explicitly invoke another constructor
}

沒有留言:

張貼留言