如何将一个构造函数的值设置为另一个构造函数的值?
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)
任何explanations/examples关于如何做到这一点都会很棒
您可以使用 this()
调用另一个构造函数。
例如:
Truck(A a){
...
}
Truck(A a,B b){
this(a);
...
...
}
只读了一本简单的Oracle手册:
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
要么
read whosebug.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;
}
...
}
我目前正在我的大学学习初级 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)
任何explanations/examples关于如何做到这一点都会很棒
您可以使用 this()
调用另一个构造函数。
例如:
Truck(A a){
...
}
Truck(A a,B b){
this(a);
...
...
}
只读了一本简单的Oracle手册:
https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html 要么 read whosebug.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;
}
...
}