是否可以从另一个(在同一类中,而不是从子类中)调用构造函数?如果是,怎么办?调用另一个构造函数的最佳方法是什么(如果有几种方法)?
当前回答
使用此关键字,我们可以在同一类中的另一个构造函数中调用一个构造函数。
示例:-
public class Example {
private String name;
public Example() {
this("Mahesh");
}
public Example(String name) {
this.name = name;
}
}
其他回答
有一些设计模式可以满足复杂构造的需要——如果不能简洁地完成,请创建工厂方法或工厂类。
通过最新的java和lambdas的添加,很容易创建一个可以接受任何初始化代码的构造函数。
class LambdaInitedClass {
public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
init.accept(this);
}
}
称之为。。。
new LambdaInitedClass(l -> { // init l any way you want });
是的,可以使用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);
}
可以通过this(…)关键字(当需要从同一类调用构造函数时)或super(…)关键词调用另一个构造函数(当您需要从超类调用构造函数时)。
但是,这样的调用必须是构造函数的第一条语句。要克服这个限制,请使用这个答案。
使用此(参数)。首选模式是从最小构造函数到最大构造函数。
public class Cons {
public Cons() {
// A no arguments constructor that sends default values to the largest
this(madeUpArg1Value,madeUpArg2Value,madeUpArg3Value);
}
public Cons(int arg1, int arg2) {
// An example of a partial constructor that uses the passed in arguments
// and sends a hidden default value to the largest
this(arg1,arg2, madeUpArg3Value);
}
// Largest constructor that does the work
public Cons(int arg1, int arg2, int arg3) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
}
}
您还可以使用最近提倡的valueOf或“of”方法:
public class Cons {
public static Cons newCons(int arg1,...) {
// This function is commonly called valueOf, like Integer.valueOf(..)
// More recently called "of", like EnumSet.of(..)
Cons c = new Cons(...);
c.setArg1(....);
return c;
}
}
要调用超级类,请使用super(someValue)。对super的调用必须是构造函数中的第一个调用,否则将出现编译器错误。
关键字this可用于从构造函数调用构造函数,当为一个类编写多个构造函数时,有时您希望从另一个构造函数调用一个构造函数以避免重复代码。
Bellow是一个链接,我解释了关于构造函数和getters()和setters()的其他主题,我使用了一个包含两个构造函数的类。我希望这些解释和例子对你有所帮助。
Setter方法或构造函数