Java Constructor Overloading

前端 未结 5 542
慢半拍i
慢半拍i 2021-01-29 16:13

I\'m new with Java and I\'m having trouble understanding the constructor issue, I have looked at many tutorials and still I\'m having difficult to understand why we use construc

5条回答
  •  既然无缘
    2021-01-29 16:45

    Actually, if you want to have 10000 constructor, you can as long a signature are differents.

    public class People {
        public People(String name, int age) {
            ...
        }
        public People(String name) {
            ...
        }
    }
    

    You can construct your object in a different way. You can see an example by yourself looking at : the java String class wich has a plenty of constructors.



    And yes, all constructors have the same name of his class.




    But this will not works :

    public class People {
        public People(String name, int age) {
            ...
        }
        public People(String name, int numberOfLegs) {
            ...
        }
    }
    

    Since you have two constructors with the same signature

提交回复
热议问题