How do I call one constructor from another in Java?

前端 未结 21 2860
不知归路
不知归路 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: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.

提交回复
热议问题