是否可以从另一个(在同一类中,而不是从子类中)调用构造函数?如果是,怎么办?调用另一个构造函数的最佳方法是什么(如果有几种方法)?


当前回答

我会告诉你一个简单的方法

构造函数有两种类型:

默认构造函数参数化构造函数

我将在一个示例中解释

class ConstructorDemo 
{
      ConstructorDemo()//Default Constructor
      {
         System.out.println("D.constructor ");
      }

      ConstructorDemo(int k)//Parameterized constructor
      {
         this();//-------------(1)
         System.out.println("P.Constructor ="+k);       
      }

      public static void main(String[] args) 
      {
         //this(); error because "must be first statement in constructor
         new ConstructorDemo();//-------(2)
         ConstructorDemo g=new ConstructorDemo(3);---(3)    
       }
   }                  

在上面的示例中,我展示了3种类型的调用

this()调用必须是构造函数中的第一条语句这是无名称对象。这将自动调用默认构造函数。3.这将调用参数化构造函数。

注:这必须是构造函数中的第一条语句。

其他回答

当我需要从代码内部调用另一个构造函数时(不是在第一行),我通常使用这样的助手方法:

class MyClass {
   int field;


   MyClass() {
      init(0);
   } 
   MyClass(int value) {
      if (value<0) {
          init(0);
      } 
      else { 
          init(value);
      }
   }
   void init(int x) {
      field = x;
   }
}

但大多数情况下,我会尽可能从第一行的简单构造函数调用更复杂的构造函数。对于以上示例

class MyClass {
   int field;

   MyClass(int value) {
      if (value<0)
         field = 0;
      else
         field = value;
   }
   MyClass() {
      this(0);
   }
}

正如大家已经说过的,您使用this(…),这称为显式构造函数调用。

但是,请记住,在这样的显式构造函数调用语句中,您可能不会引用

任何实例变量或任何实例方法或该类或任何超类中声明的任何内部类,或此或超级的

如JLS(§8.8.7.1)所述。

可以通过this(…)关键字(当需要从同一类调用构造函数时)或super(…)关键词调用另一个构造函数(当您需要从超类调用构造函数时)。

但是,这样的调用必须是构造函数的第一条语句。要克服这个限制,请使用这个答案。

是的,可以从另一个构造函数调用一个构造函数。但这有一个规则。如果从一个构造函数调用另一个构造函数,那么

该新构造函数调用必须是当前构造函数中的第一条语句

public class Product {
     private int productId;
     private String productName;
     private double productPrice;
     private String category;

    public Product(int id, String name) {
        this(id,name,1.0);
    }

    public Product(int id, String name, double price) {
        this(id,name,price,"DEFAULT");
    }

    public Product(int id,String name,double price, String category){
        this.productId=id;
        this.productName=name;
        this.productPrice=price;
        this.category=category;
    }
}

所以,下面这样的东西是行不通的。

public Product(int id, String name, double price) {
    System.out.println("Calling constructor with price");
    this(id,name,price,"DEFAULT");
}

此外,在继承的情况下,当创建子类的对象时,首先调用超级类构造函数。

public class SuperClass {
    public SuperClass() {
       System.out.println("Inside super class constructor");
    }
}
public class SubClass extends SuperClass {
    public SubClass () {
       //Even if we do not add, Java adds the call to super class's constructor like 
       // super();
       System.out.println("Inside sub class constructor");
    }
}

因此,在这种情况下,在任何其他语句之前,也会先声明另一个构造函数调用。

非常简单

public class SomeClass{

    private int number;
    private String someString;

    public SomeClass(){
        number = 0;
        someString = new String();
    }

    public SomeClass(int number){
        this(); //set the class to 0
        this.setNumber(number); 
    }

    public SomeClass(int number, String someString){
        this(number); //call public SomeClass( int number )
        this.setString(someString);
    }

    public void setNumber(int number){
        this.number = number;
    }
    public void setString(String someString){
        this.someString = someString;
    }
    //.... add some accessors
}

现在有一些额外的小功劳:

public SomeOtherClass extends SomeClass {
    public SomeOtherClass(int number, String someString){
         super(number, someString); //calls public SomeClass(int number, String someString)
    }
    //.... Some other code.
}

希望这有帮助。