【问题标题】:how to set the values of one constructor with the values of another? [duplicate]如何将一个构造函数的值设置为另一个构造函数的值? [复制]
【发布时间】:2015-12-27 07:32:20
【问题描述】:

我目前正在我的大学学习 Java 初学者课程,并且仍在学习编程的基础知识。本周我们一直在学习构造函数,而我本周任务的后半部分被困住了,因此非常感谢任何帮助。

实验室第二部分(我坚持的部分)的方向如下:

编写类中给出的卡车类的完整代码 下图。确保不要在构造函数中使用重复的代码。 例如,具有 2 个参数的构造函数应该调用一个 用 1 个参数设置圆柱体的值。

这些是它希望我制作的构造函数。

  • Truck()
  • Truck(int cylinders)
  • Truck(int cylinders, String manufacturer)
  • Truck(int cylinders, String manufacturer, double load)
  • Truck(int cylinders, String manufacturer, double load, double tow)

任何关于如何做到这一点的解释/示例都会令人惊叹

【问题讨论】:

标签: java constructor class-constructors


【解决方案1】:

您可以使用this() 调用另一个构造函数。 例如:

Truck(A a){
    ...
}
Truck(A a,B b){
    this(a);
    ...
    ...
}

【讨论】:

  • 或者谷歌Constructor overloading and constructor chaining in Java
【解决方案2】:

只需阅读简单的 Oracle 手册:

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html 要么 read stackoverflow.com more careful

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}

【讨论】:

  • 太好了,这对我帮助很大!我知道我应该用 this() 做点什么,但我不确定是什么,我需要一个完整的例子。
  • @skulltula,祝你有美好的一天
猜你喜欢
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 2016-09-19
  • 2014-03-12
  • 1970-01-01
相关资源
最近更新 更多