We overload constructors to give options on how to initialize an object.
Public Person()
{
name=""
age=""
gender=""
}
...if you override
Public Person(String name, int age, String gender)
{
this.name=name
this.age=age
this.gender=gender
}
Now upon coding time, if you need to initialize it with parameters you have two choices:
Now if you ask me what's the use?
well, since you are creating a class, you are encapsulating. you want as much to limit the use of your internal properties.
e.g.
private name
private birthyear
public Person(String name, Int age)
{
this.name=name
this.birthyear= yearNow-age
}
public Person(String name, Int birthdate)
{
this.name=name
this.birthdate=birthdate
}
You make sure that everytime a Person() is initialized, birthday property has a value either from age or birthdate.
I know the example is absurd but there are lots of complex example for this, I do overloading of constructors most of the time. from creating connection objects, to creating business process objects, since they differ in their needs.
Problem that often occur is code duplication. It's up to you to make a way to minimize/avoid duplication of code. usually I do this
public Person(String name, Int age)
{
Person(name, yearNow-age)
}
public Person(String name, Int birthyear)
{
this.name=name
this.birthyear=birthyear
Person();
}
Hope this gives an idea.
Copyright © 2026 eLLeNow.com All Rights Reserved.