【问题标题】:Problems in writing Constructors编写构造函数的问题
【发布时间】: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


【解决方案1】:

这个概念叫做构造函数链

如果我们想初始化一栋建筑物但我们不知道我们是否希望它有一个游泳池,那么我们的想法是怎么办?如果这个类的构造函数要求我们为布尔池输入一个值,我们可能会遇到问题。

所以构造函数链很有用,因为我们仍然可以在不知道所有信息的情况下初始化建筑物。

如果我们不知道我们是否想要一个池,我们将只使用这个构造函数:

public House(int length, int width, int lotLength, int lotWidth, String Owner)

你写的一切都很好。 this() 调用很好。 如果你还不清楚—— https://beginnersbook.com/2013/12/java-constructor-chaining-with-example/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-23
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多