java如何设置构造函数_构造函数如何在java中工作

好吧,我假设您没有使用Box编写class关键字,并且还省略了宽度,高度和深度声明以保存输入。

在Java中,如果您不提供任何构造函数,默认情况下默认构造函数不包含任何参数。所以如果你没有在类Box中写任何东西,你仍然可以在main中调用它的基本构造函数:

class Box{

}

class CallingClass{

public static void main(String args[]){

Box box = new Box(); // this would work.

}

}如果您提供其他一个构造函数,那么在您明确声明它之前,未声明的默认构造函数将不再可用。

class Box{

public Double height;

public Box(Double height){

this.height = height;

}

}

class CallingClass{

public static void main(String args[]){

Box box = new Box((double)50); // this would work.

Box anotherBox = new Box(); // this will give you an error.

}

}迅速超过建设者:

public Box(){...} // default constructor in which you allow caller to not worry about initialization.

public Box(Box boxToCopy){...} // copy constructor for creating a new box from the values of an old one.

public Box(double height, double width, double depth){...} // should create a box with specified dimensions.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值