开发者

SCJP Sierra Bates Chapter 2 Question 2 Default constructor calls

Background info I have a query regarding a questions from Sierra & Bates, SCJP v6 book. Namely Chapter 2 question 2. The answer given is that the "compilation fails". However when I tried this in neBeans, the code compiled and ran without error. It also returned a output of "D" which was not one of the alternatives. There are some other discussions on this same question in various forums, regarding the need to insert super() etc. However none seem to have recognised it can compile.

Question 1. I expected the constructor "Bottom2(String s)...to have called the super constructor "Top(String s)...". In which case the output would have been "BD" (which happens to be an option for the question. Why does the "Top(String s)..." not get called. 2. As there is a Top constructor then would the default compiler constructor still be implicitly created. ie in effect a "Top() {}" constructor which can be called by "Bottom2(String s)". This not how I understood this to happen - ie the compiler only creates this default if no other constructor is created. 3. Is there and error in this question, or is this a carry over question from the Java 5 version and somehow in Java 6 the compiler can now handle this. 4. Could netBeans have a means to "solve" the compiler problem. This is quite important as I am studying for the SCJP and I find not all the questions can be duplicated in netBeans. In which case I may learn to believe some co开发者_JAVA技巧de works when (for exam purposes) it does not.

Code included for ease of reference.

class Top { 
    public Top(String s) { System.out.print("B"); } 
} 

public class Bottom2 extends Top { 
    public Bottom2(String s) { System.out.print("D"); } 
    public static void main(String [] args) { 
        new Bottom2("C"); 
        System.out.println(" "); 
    }
}


Top doesn't have a default constructor (a default constructor is a public constructor with empty argument list. Therefore, the constructor of Bottom2 must explicitly invoke the super constructor (and pass its argument), but doesn't, and hence compilation fails.

Indeed, eclipse helios says:

Implicit super constructor Top() is undefined. Must explicitly invoke another constructor

and javac says:

cannot find symbol
symbol  : constructor Top()
location: class tools.Top
    public Bottom2(String s) { System.out.print("D"); }
                             ^

Are you really sure you have tried the same code in Netbeans?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜