Java之构造函数重载
下文笔者讲述构造函数的重载的简介说明
构造函数重载
构造函数运行时,根据参数的个数不同或类型不同 调用不同的构造函数
构造函数使用场景
需要支持不同的方式初始化对象
此时我们就需要创建多个构造函数,实现构造函数重载
例:
Thread类有8种构造函数
当我们不想指定线程的任何东西
就可简单地使用线程类的默认构造函数
如果我们需要指定线程名
则可以使用另一个构造函数
Thread t= new Thread ("MyThread");
简单的说:
构造函数重载其实就是在一个类中创建多个多个构造函数
例:构造函数重载示例
class Box
{
double width, height, depth;
// constructor used when all dimensions
// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions
// specified
Box()
{
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
//测试代码
public class Test
{
public static void main(String args[])
{
//使用不同的构造函数创建对象
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}
//运行以上代码,将输出以下信息
Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


