java - 如何将一个构造函数的值设置为另一个构造函数的值?

标签 java constructor class-constructors

<分区>

我目前正在我的大学学习初级 Java 类(class),并且仍在学习编程的基础知识。本周我们一直在学习构造函数,我被困在本周作业的后半部分,因此非常感谢任何帮助。

实验第二部分(我卡住的部分)的说明如下:

Write the complete code for the class Truck as given in the class diagram below. Be sure to not use duplicate code in the constructors. For example, the constructors with 2 arguments should call the one with 1 argument to set the value for cylinder.

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

  • 卡车()
  • 卡车(int cylinders)
  • Truck(int cylinders, String manufacturer)
  • Truck(int cylinders, String manufacturer, double load)
  • Truck(int cylinders, String manufacturer, double load, 双拖)

任何关于如何做到这一点的解释/例子都会很棒

最佳答案

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

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

关于java - 如何将一个构造函数的值设置为另一个构造函数的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850418/

相关文章:

macros - 向 Clojure 的 defrecord 构造函数添加功能的推荐宏?

android - Kotlin 抽象类二级构造函数

java - Android - LinearLayout不添加自定义 View

java - Spring Security 中未触发 JWT 身份验证过滤器

java - java中两个不同对象列表的交集

JAVA使用构造函数创建每个类的两个具有完整数据的对象,但出现错误

c# - 如何使用其他构造函数的参数在类中检索 HubContext (SignalR)?

java - 如何在 Java 中为构造函数编写 API 文档

c++ - 初始化模板类成员的问题

java - 带有 delaySubscription 的 rxjava onStart 事件