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

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

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



慕莱坞森
浏览 3828回答 3
3回答

慕尼黑8549860

使用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)..对超级的调用必须是构造函数中的第一个调用,否则将得到编译器错误。

千万里不及你

在Java中,同一个类的另一个构造函数可以通过this()..不过,请注意this必须在第一条线上。public class MyClass {   public MyClass(double argument1, double argument2) {     this(argument1, argument2, 0.0);   }   public MyClass(double argument1, double argument2, double argument3) {     this.argument1 = argument1;     this.argument2 = argument2;     this.argument3 = argument3;   }}那,那个this必须出现在第一行上,这看起来是一个很大的限制,但是您可以通过静态方法构造其他构造函数的参数。例如:public class MyClass {   public MyClass(double argument1, double argument2) {     this(argument1, argument2, getDefaultArg3(argument1, argument2));   }   public MyClass(double argument1, double argument2, double argument3) {     this.argument1 = argument1;     this.argument2 = argument2;     this.argument3 = argument3;   }   private static double getDefaultArg3(double argument1, double argument2) {     double argument3 = 0;     // Calculate argument3 here if you like.     return argument3;   }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java