views:

63

answers:

2
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(" ");
} }

In the above program, I guessed the output must be BD, but in the book they said the compilation fails. Can anyone explain this?

+3  A: 

The derived class Bottom2 is required to call the base class constructor using super, otherwise you'll get a compile error. For example, if you do this, it will compile:

public Bottom2(String s) { super(s); System.out.print("D"); }

See the section on Subclass Constructors.

casablanca
+2  A: 

When you have public Top(String s) then java doesn't create the default constructor with no arguments then when you write the child class, the constructor look for the default constructor (because you are not calling explictly)... then the compilations fails.

leo