How do I call one constructor from another in Java?

前端 未结 21 2506
不知归路
不知归路 2020-11-22 01:06

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if th

21条回答
  •  花落未央
    2020-11-22 01:13

    [Note: I just want to add one aspect, which I did not see in the other answers: how to overcome limitations of the requirement that this() has to be on the first line).]

    In Java another constructor of the same class can be called from a constructor via this(). Note however that this has to be on the first line.

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

    That this has to appear on the first line looks like a big limitation, but you can construct the arguments of other constructors via static methods. For example:

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

提交回复
热议问题