为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕莱坞森 2019-06-21 13:41:16
如何在Java中从另一个构造函数中调用一个构造函数?是否可以从另一个类(在同一个类中,而不是从子类中)调用构造函数?如果是,怎么做?调用另一个构造函数的最佳方法是什么(如果有几种方法)?
查看完整描述

3 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

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


查看完整回答
反对 回复 2019-06-21
?
千万里不及你

TA贡献1784条经验 获得超9个赞

在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;

  }}


查看完整回答
反对 回复 2019-06-21
  • 3 回答
  • 0 关注
  • 3826 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号