Java中的构造函数链

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4183256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:25:37  来源:igfitidea点击:

Constructor Chaining in Java

javaclassmethods

提问by David Brown

I hava slight doubt regarding the Output of the Program of Constructor Chaining I showed Below:

我对下面显示的构造函数链接程序的输出有一些疑问:

class Cube {

    int length;
    int breadth;
    int height;
    public int getVolume() {
        return (length * breadth * height);
    }
    Cube() {
        this(10, 10);
        System.out.println("Finished with Default Constructor of Cube");
    }
    Cube(int l, int b) {
        this(l, b, 10);
        System.out.println("Finished with Parameterized Constructor having
                                    2 params of Cube");
    }
    Cube(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
        System.out.println("Finished with Parameterized Constructor having
                                    3 params of Cube");
    }
}

public class SpecialCube extends Cube {

    int weight;
    SpecialCube() {
        super();
        weight = 10;
    }
    SpecialCube(int l, int b) {
        this(l, b, 10);
        System.out.println("Finished with Parameterized Constructor having
                                    2 params of SpecialCube");
    }
    SpecialCube(int l, int b, int h) {
        super(l, b, h);
        weight = 20;
        System.out.println("Finished with Parameterized Constructor having
                                    3 params of SpecialCube");
    }
    public static void main(String[] args) {
        SpecialCube specialObj1 = new SpecialCube();
        SpecialCube specialObj2 = new SpecialCube(10, 20);
        System.out.println("Volume of SpecialCube1 is : "
                + specialObj1.getVolume());
        System.out.println("Weight of SpecialCube1 is : "
                + specialObj1.weight);
        System.out.println("Volume of SpecialCube2 is : "
                + specialObj2.getVolume());
        System.out.println("Weight of SpecialCube2 is : "
                + specialObj2.weight);
    }
}

OUTPUT:

输出:

Finished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20

The doubt is regarding the OutPut that how "1000", "10", "2000" & "20" are achiueved?

疑问是关于 OutPut 是如何实现“1000”、“10”、“2000”和“20”的?

In the main Class We have created two Objects :

在主类中,我们创建了两个对象:

SpecialCube specialObj1 = new SpecialCube();
SpecialCube specialObj2 = new SpecialCube(10, 20);

First with "No Parameters" and Second with "Two Parameters", The First Constructor Cube() with "No Parameter" has only two values this(10,10)and the one with "Two Parameters" has the values

第一个带有“无参数”,第二个带有“两个参数”,带有“无参数”的第一个构造函数 Cube() 只有两个值this(10,10),而带有“两个参数”的一个有值

Cube(int l, int b) 
    {this(l, b, 10);}

I don't understand how the Below OutPuts are generated.

我不明白下面的输出是如何生成的。

Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20

Please Can anybody help me!

请任何人都可以帮助我!

Thanks, david

谢谢,大卫

采纳答案by AlexR

I think it is obvious. specialObj1 is created during default constructor that invokes 1 argument constructor, that invokes 3 argument constructor. Each invocation sends 10 as value of cube dimension. So, volume is 10*10*10 = 1000;

我认为这是显而易见的。specialObj1 是在调用 1 个参数构造函数的默认构造函数期间创建的,该构造函数调用 3 个参数构造函数。每次调用发送 10 作为多维数据集维度的值。所以,体积是 10*10*10 = 1000;

weight is not method. It is field that is initialized in default and 3-arg constructor. Due to first thing the constructor does is call of this(...) it does not matter what value is assigned to this variable in other constructors. The first constructor in chain actually overrides all previously set values. This is a reason why weight = 10 for the first object.

重量不是方法。它是在默认和 3-arg 构造函数中初始化的字段。由于构造函数所做的第一件事是调用 this(...),因此在其他构造函数中为此变量分配了什么值并不重要。链中的第一个构造函数实际上覆盖了所有先前设置的值。这就是为什么第一个物体的重量 = 10 的原因。

Second object is created using 2-arg constructor that is called with parameters 10 and 20, so volume is 10*20*10 = 2000. (second 10 is set when 2args constructor calls 3args constructor.) In case of second object the weight is set by 3-args constructor, because 2-args constructor does not override this value.

第二个对象是使用参数 10 和 20 调用的 2-arg 构造函数创建的,因此体积为 10*20*10 = 2000。(当 2args 构造函数调用 3args 构造函数时设置第二个 10。)如果是第二个对象,则权重为由 3-args 构造函数设置,因为 2-args 构造函数不会覆盖此值。

I hope this helps.

我希望这有帮助。

回答by Jon Skeet

Well, let's take one case at a time. For the first version, the constructor chain goes:

好吧,让我们一次处理一个案例。对于第一个版本,构造函数链如下:

SpecialCube()
Cube()
Cube(10, 10)
Cube(10, 10, 10)

So the cube ends up with a volume of 1000, and the default weight of 10 (as specified in the SpecialCubeparameterless constructor).

所以立方体最终的体积为 1000,默认权重为 10(在无SpecialCube参数构造函数中指定)。

In the second case, the constructor chain looks like this:

在第二种情况下,构造函数链如下所示:

SpecialCube(10, 20)
SpecialCube(10, 20, 10)
Cube(10, 20, 10)

and the weight is set to 20 by the SpecialCube(int l, int b, int h)parameterless constructor - so we have a volume of 2000 and a weight of 20.

并且无SpecialCube(int l, int b, int h)参数构造函数将权重设置为 20 - 所以我们的体积为 2000,权重为 20。

If that still doesn't explain everything to you, please ask a very specific question - ideally about oneof the cases, stating which bit you don't understand.

如果这仍然不能向您解释所有内容,请提出一个非常具体的问题 - 最好是关于其中一种情况,说明您不明白哪一点。

回答by Andreas Dolk

When you call SpecialCube(), the flow is like this (pseudo-code):

当你调用时SpecialCube(),流程是这样的(伪代码):

SpecialCube()
  -> Cube()
     -> Cube(10,10)
        -> Cube(10,10,10)
           l:=10, b:=10, h:=10
           print message "Finished with Parameterized Constructor having 3 params of Cube"
        print message "Finished with Parameterized Constructor having 2 params of Cube"
     print message "Finished with Default Constructor of Cube"
  weight:=10

And at the end you have a cube constructed with (l,b,h) = (10,10,10)

最后你有一个立方体构造 (l,b,h) = (10,10,10)

回答by Nim

Break it down:

分解一下:

SpecialCube1is defaultconstructed, so calls default constructor SpecialCube(), which in turn calls super(), which default constructs Cube(), that will explain the first two.

SpecialCube1默认构造的,因此调用默认构造函数SpecialCube(),后者又调用super(),默认构造Cube(),这将解释前两个。

where as the SpecialCube2follows the proper constructor chain of SpecialCube.

其中.SpecialCube2的正确构造函数链如下所示SpecialCube

回答by viramalla pradeep

here these outputs are generated because

在这里生成这些输出是因为

volume of SpecialCube1 is : 1000 //when first time getVolume function is called ,it is getting 10,10,10, as arguments observe the following code where l,b,h values are assigned to length,breadth,height

SpecialCube1的体积是:1000 //当第一次调用getVolume函数时,它得到10,10,10,作为参数观察下面的代码,其中l,b,h值被分配给长度,宽度,高度

Cube(int l, int b, int h) {
//l=10,b=10,h=10

System.out.println(l);
System.out.println(b);
System.out.println(h);
    length = l;
    breadth = b;
    height = h;

Weight of SpecialCube1 is : 10 //in the first constr weight is assigned to 10 (ie 1st object)

SpecialCube1的权重是:10 //在第一个constr中权重被赋值为10(即第一个对象)

Volume of SpecialCube2 is : 2000 // for the second time getVolume function is getting arguments from specialcube(3 argmted constr ie 10,20,10;

SpecialCube2 的体积是:2000 // 第二次 getVolume 函数从 specialcube(3 argmted constr ie 10,20,10;

SpecialCube(int l, int b, int h) 
{
//l=10,b=20,h=10
    super(l, b, h);
    System.out.println(l);
System.out.println(b);
System.out.println(h);
    weight = 20;

Weight of SpecialCube2 is : 20 //in the 2nd constr weight is assigned to 20 (ie 1st object)

SpecialCube2的权重为:20 //在第二个constr中权重分配给20(即第一个对象)

SpecialCube(int l, int b, int h) { //l=10,b=20,h=10

SpecialCube(int l, int b, int h) { //l=10,b=20,h=10

    super(l, b, h);
    System.out.println(l);
System.out.println(b);
System.out.println(h);
    weight = 20;

回答by Mak.bloke

Here below the flow of execution,

下面是执行流程,

step 1 : When " SpecialCube specialObj1 = new SpecialCube();" executed, the default constructor "SpecialCube()" will be called.

第 1 步:当“SpecialCube specialObj1 = new SpecialCube();” 执行时,将调用默认构造函数“SpecialCube()”。

Step 2 : Now "Super()" will be excuted to call "SpecialCube's" super Class "Cube".

第 2 步:现在将执行“Super()”以调用“SpecialCube”的超类“Cube”。

Step 3 : Now "this(10,10)" in super class "cube" will be executed, which will call constructor of 2 parameters from the same class "cube" , i.e. "Cube(int l,int b)" by passing parameters(l=10,b=10).

第 3 步:现在将执行超类“cube”中的“this(10,10)”,它将通过传递调用来自同一类“cube”的 2 个参数的构造函数,即“Cube(int l,int b)”参数(l=10,b=10)。

Step 4 : Now "this(l,b,10) will be executed with actual parameter passed in step#3 is "this(10,10,10)", which will call 3 parameterized constructor "Cube(int l, int b, int h)", with passing values from step#3, it will be like "Cube(int l=10,int b=10,int h=10)".

第 4 步:现在“this(l,b,10) 将使用第 3 步中传递的实际参数执行”是“this(10,10,10)”,它将调用 3 个参数化构造函数“Cube(int l, int b)” , int h)”,通过步骤#3 传递的值,它将类似于“Cube(int l=10,int b=10,int h=10)”。

Step 5: instance variables like length = 10, breadth=10, heigth=10 for the the object "specialObj1" created at step # 1.

第 5 步:在第 1 步中创建的对象“specialObj1”的实例变量,如长度 = 10、宽度 = 10、高度 = 10。

Step 6: Then java will assign "Weight" variable as 10 in the constructor "SpecialCube()". (Refer step # 1)

第 6 步:然后 java 将在构造函数“SpecialCube()”中将“Weight”变量赋值为 10。(请参阅第 1 步)

Now see method execution for object "SpecialCube()" (I am just considering only "specialObj1".

现在查看对象“SpecialCube()”的方法执行(我只考虑“specialObj1”。

Step 7 : System.out.println("Volume of SpecialCube1 is : "+ specialObj1.getVolume()); , when this statement executed, java will call the super class "Cube's" "getVolume()" method , since subclass "SpecialCube" inheriates its by keyword "extends", refer below in your sublass.

Step 7 : System.out.println("SpecialCube1的体积是:"+ specialObj1.getVolume()); ,当这条语句执行时,java将调用超类“Cube's”的“getVolume()”方法,因为子类“SpecialCube”通过关键字“extends”继承了它,请参考下面你的子类。

public class SpecialCube extends Cube

公共类 SpecialCube 扩展了 Cube

step 8 : Step 1 thru 5, already assigned instanace variable as "length = 10, breadth=10, heigth=10", your getting volume as "1000".

第 8 步:第 1 步到第 5 步,已将实例变量分配为“长度 = 10,宽度 = 10,高度 = 10”,您的获取量为“1000”。

step 9: "System.out.println("Weight of SpecialCube1 is : "+ specialObj1.weight); - this statement print the "weight" variable value as "10", because of step #6.

第 9 步:"System.out.println("SpecialCube1 的权重为:"+ specialObj1.weight); - 由于第 6 步,此语句将“权重”变量值打印为​​“10”。

Hope, it will explain the reason.Try the same flow for object "specialObj2".

希望它会解释原因。对对象“specialObj2”尝试相同的流程。