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


当前回答

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

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

其他回答

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

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

是的,一个类中可以存在任意数量的构造函数,它们可以由另一个构造函数使用this()调用[请不要将this()构造函数调用与this关键字混淆]。this()或this(args)应该是构造函数中的第一行。

例子:

Class Test {
    Test() {
        this(10); // calls the constructor with integer args, Test(int a)
    }
    Test(int a) {
        this(10.5); // call the constructor with double arg, Test(double a)
    }
    Test(double a) {
        System.out.println("I am a double arg constructor");
    }
}

这被称为构造函数重载。请注意,对于构造函数,只有重载概念才适用,而不是继承或重写。

在构造函数中,可以使用this关键字调用同一类中的另一个构造函数。这样做称为显式构造函数调用。

这是另一个矩形类,其实现与对象部分中的实现不同。

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(1, 1);
    }
    public Rectangle(int width, int height) {
        this( 0,0,width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

}

此类包含一组构造函数。每个构造函数初始化矩形的部分或全部成员变量。

是的,可以使用this()从另一个构造函数调用一个构造函数

class Example{
   private int a = 1;
   Example(){
        this(5); //here another constructor called based on constructor argument
        System.out.println("number a is "+a);   
   }
   Example(int b){
        System.out.println("number b is "+b);
   }

非常简单

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.
}

希望这有帮助。