【发布时间】:2020-04-04 08:06:18
【问题描述】:
(学习 OOP 概念后的第一次练习。答案要简单一些)
(我只是按照技能测试作业中的说明进行操作;这就是为什么我不讨论其他类和文件的逻辑)
我必须在一个类中添加 3 个构造函数,该类本身是从父类扩展而来的。
第一个构造函数使用与父类构造函数相同的参数。
第二个和第三个构造函数分别不断加参数。
我对第二个和第三个构造函数的语法感到困惑。
public class House
extends Building {
// TODO - Put your code here.
private String mOwner;
private boolean mPool;
//This constructor exists in Building class. So, I can use it here with super keyword. Right?
public House(int length, int width, int lotLength, int lotWidth){
super(length, width, lotLength, lotWidth);
}
//Is using "this" keyword okay here? I am just using the constructor existing in this file.
public House(int length, int width, int lotLength, int lotWidth, String Owner){
this(length, width, lotLength, lotWidth);
mOwner = Owner;
}
// Is this right?
public House(int length, int width, int lotLength, int lotWidth, String Owner, boolean pool){
this(length, width, lotLength, lotWidth, Owner);
mPool = pool;
}
}
【问题讨论】:
-
我会说这很好,你也可以使用相同的超级构造函数并单独添加它们,
-
@devgianlu 这在设计上并不完全正确,因为它会通过直接调用超级构造函数来忽略
House构造函数完成的任何 潜在 初始化。在这种情况下,这无关紧要,但如果最小参数的构造函数做了不同的事情,它会改变行为(或者你需要将它添加到所有构造函数中)。 -
请完善您问题的摘要和正文。目前还不清楚你到底在问什么。可能,Builder 模式是您正在寻找的东西:howtodoinjava.com/design-patterns/creational/…
-
@Kayaman 你能举个例子吗?在这种情况下,我有兴趣了解构造函数的行为。
-
好吧,假设您将
System.out.println("House initialized");添加到第一个构造函数中。如果您要从其他构造函数调用super(),它将不会被打印。所以问题中的代码是正确的,您不希望其他构造函数调用super()并分配所有变量。这将需要更多的写作,并成为潜在的错误来源。
标签: java oop constructor this super