[英]Can objects have instance variables declared in constructor?
这肯定是一个愚蠢的问题,但是我想知道这个问题,因为有时当我创建特定类的对象时,我并不总是希望该对象具有所有实例变量,因为它们不会被使用。 这使我想到,如果在某些情况下特定类的对象有时仅应具有一个额外的实例变量的情况下,构造函数是否是创建实例变量的好地方。 当然,如果可能的话。 在下面的情况下,它是实例变量depth
,但是在其他情况下,它可能不那么琐碎。
例如在2D项下的类应该由从3D项目不同depth
的实例变量,因为2D项目没有任何深度:
class Box {
int width, height, depth, surface;
public Box(int width, int height) { //2d box
this.width = width;
this.height = height;
surface = width*height;
}
public Box(int width, int height, int depth) { //3d box
this.width = width;
this.height = height;
this.depth = depth;
surface = width*height*depth;
}
public getDepth() {
return this.depth;
}
}
0
对吗? 实例类型int变量的默认值。 您已经自己回答了所有问题。
使用诸如Shape的基类,其中包含高度和宽度。 然后2DShape和3DShape扩展了Shape类并定义了自己的实例变量。 Shape类也可以具有抽象方法来定义面积,体积等。
不,你不能那样做。
是的,因为int
的值默认为0
,所以它将返回0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.