how to set the values of one constructor with the values of another?
本问题已经有最佳答案,请猛点这里访问。
我目前在我的大学的初级Java课程,我仍然在学习编程的基本知识。这周我们一直在学习建设者,而我在这周的任务的后半部分被卡住了,所以任何帮助都会非常感谢。
实验室第二部分(我被卡住的部分)的说明如下:
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.
这些是它要我做的构造器。
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)
关于如何做到这一点的任何解释/例子都会令人惊讶。
您可以使用
1 2 3 4 5 6 7 8 | Truck(A a){ ... } Truck(A a,B b){ this(a); ... ... } |
只需阅读一本简单的Oracle手册:
https://docs.oracle.com/javase/tutorial/java/javaoo/thiskey.html或阅读stackoverflow.com更小心
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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; } ... } |