Java Constructor Overloading

人走茶凉 提交于 2019-12-02 13:44:13

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
{
}

Yes a constructor has the same name as the Class.

As long as the constructors have different signatures you can have as many as you want. The signature is what distinguishes one constructor from another...

public MyClass()
{
}

public MyClass(int a)
{
}

public MyClass(int a, int b)
{
}

public MyClass(String a)
{
}

public MyClass(int a, String b)
{
}

Those are all different because they have different signatures.

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

The constructors purpouse is to contain the code to inizialize the object. Usually, the initialization is done using constructor parameters. You can have different constructors with different parameters list, as needed by your context. It is a good pratice to do constructor chaining, that is calling a base constructor from others.

Adding to the @brso05 answer,

This is also one of the ways:

public MyClass( int a)
{
}

public MyClass( int a, int b)
{
}

public MyClass( int a, String b)
{
}

And So on..It is the arguments which make difference, rest remains the same!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!