How do I call one constructor from another in Java?

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

    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

提交回复
热议问题