Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用另一个类的变量实现构造函数?_Java - Fatal编程技术网

Java 使用另一个类的变量实现构造函数?

Java 使用另一个类的变量实现构造函数?,java,Java,我是一名java初学者,希望得到一些帮助来实现我的构造函数 比如说 public Class WidthLenth { private double width; private double length; public WidthLength(double width, double length) { this.width = width; this.length = length; } public double getWidth() { return width; } publi

我是一名java初学者,希望得到一些帮助来实现我的构造函数

比如说

public Class WidthLenth {
private double width;
private double length;

public WidthLength(double width, double length) {
this.width = width;
this.length = length;
}

public double getWidth() {
return width;
}

public double getLength() {
return length;
}
在另一节课上

public Class Rectangle {
private WidthLength widthLength <-- there is a uni-directional relationship here
private String color
那么方法呢

public getWidthLenth() {
}
会有用的


如何实现此构造函数?

您只需在构造函数中创建一个新的
WidthLength
对象

public Rectangle(double width, double length, String col)
{
    widthLength = new WidthLength(width, length);
    color = col;
}
试试这个:

public Rectangle(double width, double length, String color) {
    this.widthLength = new WidthLength(width, length);
    this.color = color;
}

public WidthLength getWidthLength() {
    return this.widthLength;
}
public Rectangle(double width, double length, String color) {
    this.widthLength = new WidthLength(width, length);
    this.color = color;
}

public WidthLength getWidthLength() {
    return this.widthLength;
}