是否可以从另一个(在同一类中,而不是从子类中)调用构造函数?如果是,怎么办?调用另一个构造函数的最佳方法是什么(如果有几种方法)?
当前回答
您可以使用“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;
}
}
最初来自米尔科·克莱姆(Mirko Klemm)的回答,为了解决这个问题,稍作修改:
为了完整起见:还有实例初始化块,它总是在调用任何其他构造函数之前执行。它只是由类定义正文中某个位置的语句块“{…}”组成。你甚至可以有不止一个。你不能调用它们,但如果你想在构造函数之间重用一些代码,它们就像“共享构造函数”代码,类似于调用方法。
所以在你的情况下
{
System.out.println("this is shared constructor code executed before the constructor");
field1 = 3;
}
还有一个“静态”版本用于初始化静态成员:“静态{…}”
从另一个构造函数调用构造函数
class MyConstructorDemo extends ConstructorDemo
{
MyConstructorDemo()
{
this("calling another constructor");
}
MyConstructorDemo(String arg)
{
System.out.print("This is passed String by another constructor :"+arg);
}
}
也可以使用super()调用调用父构造函数
您可以使用“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构造函数。。
是的,可以使用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);
}