Java Constructor Overloading

前端 未结 5 499
慢半拍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:46

    a) is it because the constructors have to be with the same name as the class and we need to distinguish between them ?

    Yes constructors are always the name of the class without any return type, and in order to distinguish between them, you can have different parameters.

    b) what if i want to add a third constructor ? it can be also int type ?

    Yes, you can add any no. of overloaded constructors but those all should be different in no. and/or type of parameters.

    Like :-

    public User() // default constructor
    {
    }
    
    public User(int age) // overloaded constructor with int
    {
    }
    
    public User(String name) // // overloaded constructor with String
    {
    }
    
    public User(String name, int age) // // overloaded constructor with String and int
    {
    }
    

提交回复
热议问题