java 调用其他构造函数_如何在Java中从另一个构造函数中调用一个构造函数?

使用this(args)..首选的模式是从最小的构造函数到最大的构造函数。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;

}}

您还可以使用最近提倡的价值或公正的“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)..对超级的调用必须是构造函数中的第一个调用,否则将得到编译器错误。


版权声明:本文为weixin_33722350原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。