Java-重载-构造函数
时间:2020-02-23 14:36:44 来源:igfitidea点击:
在本教程中,我们将学习Java编程语言中的构造函数重载。
我们在"类-构造函数"教程中了解了构造函数。
构造函数重载类似于方法重载。
什么是Java中的构造方法重载?
在Java类中,当我们有多个具有不同参数声明的构造函数时,则称这些构造函数被重载,并且该过程称为构造函数重载。
语法
class NameOfTheClass { //constructor overloading NameOfTheClass() { //some code... } NameOfTheClass(list_of_params1) { //some code... } NameOfTheClass(list_of_params2) { //some code... } }
其中,NameOfTheClass是类的名称,它具有3个与该类共享相同名称但具有不同参数声明的构造函数。
范例1:
在下面的示例中,我们具有PackagingBox
类。
我们将使用构造函数重载来初始化其尺寸。
class PackagingBox { //member variables private double length; private double breadth; private double height; //constructor overloading //if dimensions not specified PackagingBox() { this.length = 0; this.breadth = 0; this.height = 0; } //if dimensions specified PackagingBox(double length, double breadth, double height) { this.length = length; this.breadth = breadth; this.height = height; } //method public void showDimensions() { System.out.println("Length: " + this.length); System.out.println("Breadth: " + this.breadth); System.out.println("Height: " + this.height); } public double getVolume() { return this.length * this.breadth * this.height; } } class ConstructorOverloadingExample { public static void main(String[] args) { //create object //no dimension is set PackagingBox myBox1 = new PackagingBox(); System.out.println("Dimension of box 1:"); myBox1.showDimensions(); System.out.println("Volume of box 1: " + myBox1.getVolume()); //setting dimension PackagingBox myBox2 = new PackagingBox(10, 20, 30); System.out.println("Dimension of box 2:"); myBox2.showDimensions(); System.out.println("Volume of box 2: " + myBox2.getVolume()); } }
$javac ConstructorOverloadingExample.java $java ConstructorOverloadingExample Dimension of box 1: Length: 0.0 Breadth: 0.0 Height: 0.0 Volume of box 1: 0.0 Dimension of box 2: Length: 10.0 Breadth: 20.0 Height: 30.0 Volume of box 2: 6000.0