为什么需要使用多个构造函数?

Tre*_*n46 7 java constructor

我现在正在学习 Java,刚刚了解了什么是构造函数。如果您需要初始化所有变量,我不明白为什么您需要多个构造函数。

Zer*_*ero 7

简而言之,为了方便起见(第一个示例)或允许完全不同的初始化方法或不同的源类型(第二个示例),您可以使用多个构造函数。

您可能需要多个构造函数来实现您的类,以允许省略一些已经设置的参数:

//The functionality of the class is not important, just keep in mind parameters influence it.
class AirConditioner{
   enum ConditionerMode{
      Automatic, //Default
      On,
      Off
   }
   public ConditionerMode Mode; //will be on automatic by default.
   public int MinTemperature = 18;
   public int MaxTemperature = 20;

   public AirConditioner(){ //Default constructor to use default settings or initialize manually.
      //Nothing here or set Mode to Automatic. 
   }

   //Mode
   public AirConditioner(ConditionerMode mode){ //Setup mode, but leave the rest at default
      Mode = mode;
   }
   //setup everything.
   public AirConditioner(ConditionerMode mode, int MinTemp, int MaxTemp){
      Mode = mode;
      MinTemperature = MinTemp;
      MaxTemperature = MaxTemp;
   }
}
Run Code Online (Sandbox Code Playgroud)

另一个例子是当不同的构造函数遵循不同的过程来初始化变量时。例如,您可以有一个仅显示文本表的数据表。构造函数可以从数据库或文件中获取数据:

class DataTable{
   public DataTable(){} //Again default one, in case you want to initialize manually

   public DataTable(SQLConnection con, SQLCommand command){
      //Code to connect to database get the data and fill the table
   }

   public DataTable(File file){
      //Code to read data from a file and fill the table
   }
}
Run Code Online (Sandbox Code Playgroud)


Har*_*ist 4

一个类可以有多个构造函数,只要它们的签名(它们采用的参数)不同即可。您可以根据需要定义任意多个构造函数。当一个Java类包含多个构造函数时,我们说该构造函数是重载的(有多个版本)。这就是构造函数重载的含义,即一个 Java 类包含多个构造函数。

话虽如此,是否要在类中创建多个构造函数完全取决于您的实现,但在许多情况下拥有多个构造函数可以让您的生活更轻松。假设下面的类没有默认构造函数:

public class Employee {

    private int age;
    private String name;

    Employee(int age, String name){
        this.age=age;
        this.name=name;     
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,在创建此类对象时,用户只有在手边有年龄和名称参数时才能这样做,这限制了 Java 对象的真正功能,因为对象的状态应该能够在初始化后随时修改和填充。