我正在编写Triangle类的两个构造函数,它们作为参数:String,integer和double数组
private double [] side = new double[3];
public Triangle() {
this("",0,side);
//Here I have a compile error says "Cannot refer to an instance field side while explicitly invoking a constructor"
}
public Triangle(String color, int opacity,double [] side) {
super(color, opacity);
this.side = side ;
}
Run Code Online (Sandbox Code Playgroud)
在主要方法中,我想初始化三角形,但直到现在我才能这样做..
我试过这两种方式,但没有它们起作用
GeoShapes[1] = new Triangle( "Red" , 89 , {2,4,3} ) ;
GeoShapes[2] = new Triangle( "white", 68 , new double{5,6,3} );
Run Code Online (Sandbox Code Playgroud)
注意:我确实尝试初始化一个数组,然后将其引用放在第三个参数中,它可以工作,但这不是我需要的
任何人都可以帮助我在第三个参数中写什么?
你必须像这样使用它:
geoShapes[1] = new Triangle("Red" , 89 , new double[] {2,4,3});
Run Code Online (Sandbox Code Playgroud)
您只能在声明点或数组创建表达式中使用数组初始值设定项.
另一种选择是使用varargs参数类型:
public Triangle(String color, int opacity, double... side) {
super(color, opacity);
this.side = side ;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用:创建实例:
geoShapes[1] = new Triangle("Red", 89 , 2, 4, 3);
Run Code Online (Sandbox Code Playgroud)
关于0-arg构造函数中的问题:
public Triangle() {
this("",0,side);
}
Run Code Online (Sandbox Code Playgroud)
您正在尝试将实例字段传递side给参数化构造函数,该构造函数无效,因为side尚未初始化.所有的初始化工作都完成后,this()或super()调用.您应该创建一个数组并像通常那样传递它.这样可行:
public Triangle() {
this("", 0, new double[] {0, 0, 0});
}
Run Code Online (Sandbox Code Playgroud)
请遵循适当的Java命名约定.变量名以小写字母开头.
| 归档时间: |
|
| 查看次数: |
3409 次 |
| 最近记录: |