How do I call one constructor from another in Java?

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

    Yes, any number of constructors can be present in a class and they can be called by another constructor using this() [Please do not confuse this() constructor call with this keyword]. this() or this(args) should be the first line in the constructor.

    Example:

    Class Test {
        Test() {
            this(10); // calls the constructor with integer args, Test(int a)
        }
        Test(int a) {
            this(10.5); // call the constructor with double arg, Test(double a)
        }
        Test(double a) {
            System.out.println("I am a double arg constructor");
        }
    }
    

    This is known as constructor overloading.
    Please note that for constructor, only overloading concept is applicable and not inheritance or overriding.

提交回复
热议问题