是否可以从另一个(在同一类中,而不是从子类中)调用构造函数?如果是,怎么办?调用另一个构造函数的最佳方法是什么(如果有几种方法)?
当前回答
正如大家已经说过的,您使用this(…),这称为显式构造函数调用。
但是,请记住,在这样的显式构造函数调用语句中,您可能不会引用
任何实例变量或任何实例方法或该类或任何超类中声明的任何内部类,或此或超级的
如JLS(§8.8.7.1)所述。
其他回答
有一些设计模式可以满足复杂构造的需要——如果不能简洁地完成,请创建工厂方法或工厂类。
通过最新的java和lambdas的添加,很容易创建一个可以接受任何初始化代码的构造函数。
class LambdaInitedClass {
public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
init.accept(this);
}
}
称之为。。。
new LambdaInitedClass(l -> { // init l any way you want });
您可以使用“this”关键字从同一类的另一个构造函数中创建构造函数。示例-
class This1
{
This1()
{
this("Hello");
System.out.println("Default constructor..");
}
This1(int a)
{
this();
System.out.println("int as arg constructor..");
}
This1(String s)
{
System.out.println("string as arg constructor..");
}
public static void main(String args[])
{
new This1(100);
}
}
输出-字符串作为arg构造函数。。默认构造函数。。int作为arg构造函数。。
使用此关键字,我们可以在同一类中的另一个构造函数中调用一个构造函数。
示例:-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
在构造函数中,可以使用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(…),这称为显式构造函数调用。
但是,请记住,在这样的显式构造函数调用语句中,您可能不会引用
任何实例变量或任何实例方法或该类或任何超类中声明的任何内部类,或此或超级的
如JLS(§8.8.7.1)所述。