开发者

SCJP v6 (Sierra,Bates) Chapter 2, Question 12 Interpretations of constructor calls

Could I have some feedback on this

Given "new House("x ")" sends a string I had expected that the "House(String name)" constructor would have called the Building super class constructor "Building(String name)". In which case the answer would have been "bn x h hn x". However the answer is "b h hn x" (and yes it does run with that output).

Questions 1. Other than a call "new Building("string_value")" would there be a situation when House would call the "Building(String name)" constructor? (ie other than additional code in the House constructors? 2.Why is it that the no argument Building constructor is called, rather than the overloa开发者_开发知识库ded Building (String name) constructor? What I am looking is a possibility there could be many Building constructors and there could be a need to call specific super constructors from subclasses. How do you ensure which constructor (given two or more choices) is called?

Code included for ease of reference.

The answer is "b h hn x"

class Building {
    Building() {System.out.print("b ");}
    Building(String name) {this(); System.out.print("bn "+name);}
}

public class House extends Building {
    House() {System.out.print("h ");}
    House(String name) { this();System.out.print("hn "+name);}

    public static void main(String a[]) {
        new House("x "); }
}

Regards Scott


If no explicit superclass constructor call is provided, and no call to a constructor in the same class is provided either, the no-args superclass constructor is always called. That's how Java is designed, and it would be too complicated and inefficient for the JVM to record which was the first constructor called and try and match it up with a superclass constructor.

If you needed to call a different superclass constructor, you would just call it explicitly, like this:

super(foo,bar);


When inheriting from another class, you must call super() in your constructor. If you don't, the compiler will insert that call for you as you can plainly see.

The superclass constructors are called because otherwise the object would be left in an uninitialized state.

Your program execution order is given below:

  1. new House("x "); // call in main this will call same class default constructor because of this(), as you knew already that first statement must be either this() or super() if any

  2. Call to this() in above constructor executes House() constructor. Now in House() there is no this() call so compiler puts default super() which will call base class default constructor and

hence the output is b h hn x

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜