How do I call one constructor from another in Java?

前端 未结 21 2397
不知归路
不知归路 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;
    
      }
    
    }
    
    0 讨论(0)
  • 2020-11-22 01:13

    There are design patterns that cover the need for complex construction - if it can't be done succinctly, create a factory method or a factory class.

    With the latest java and the addition of lambdas, it is easy to create a constructor which can accept any initialization code you desire.

    class LambdaInitedClass {
    
       public LamdaInitedClass(Consumer<LambdaInitedClass> init) {
           init.accept(this);
       }
    }
    

    Call it with...

     new LambdaInitedClass(l -> { // init l any way you want });
    
    0 讨论(0)
  • 2020-11-22 01:13

    Yes, you can call constructors from another constructor. For example:

    public class Animal {
        private int animalType;
    
        public Animal() {
            this(1); //here this(1) internally make call to Animal(1);
        }
    
        public Animal(int animalType) {
            this.animalType = animalType;
        }
    }
    

    you can also read in details from Constructor Chaining in Java

    0 讨论(0)
  • 2020-11-22 01:14

    Yes it is possible to call one constructor from another. But there is a rule to it. If a call is made from one constructor to another, then

    that new constructor call must be the first statement in the current constructor

    public class Product {
         private int productId;
         private String productName;
         private double productPrice;
         private String category;
    
        public Product(int id, String name) {
            this(id,name,1.0);
        }
    
        public Product(int id, String name, double price) {
            this(id,name,price,"DEFAULT");
        }
    
        public Product(int id,String name,double price, String category){
            this.productId=id;
            this.productName=name;
            this.productPrice=price;
            this.category=category;
        }
    }
    

    So, something like below will not work.

    public Product(int id, String name, double price) {
        System.out.println("Calling constructor with price");
        this(id,name,price,"DEFAULT");
    }
    

    Also, in the case of inheritance, when sub-class's object is created, the super class constructor is first called.

    public class SuperClass {
        public SuperClass() {
           System.out.println("Inside super class constructor");
        }
    }
    public class SubClass extends SuperClass {
        public SubClass () {
           //Even if we do not add, Java adds the call to super class's constructor like 
           // super();
           System.out.println("Inside sub class constructor");
        }
    }
    

    Thus, in this case also another constructor call is first declared before any other statements.

    0 讨论(0)
  • 2020-11-22 01:14

    You can call another constructor via the this(...) keyword (when you need to call a constructor from the same class) or the super(...) keyword (when you need to call a constructor from a superclass).

    However, such a call must be the first statement of your constructor. To overcome this limitation, use this answer.

    0 讨论(0)
  • 2020-11-22 01:15

    Calling constructor from another constructor

    class MyConstructorDemo extends ConstructorDemo
    {
        MyConstructorDemo()
        {
            this("calling another constructor");
        }
        MyConstructorDemo(String arg)
        {
            System.out.print("This is passed String by another constructor :"+arg);
        }
    }
    

    Also you can call parent constructor by using super() call

    0 讨论(0)
提交回复
热议问题