Constructor Overloading (java)
CONSTRUCTOR OVERLOADING (java)
example of a class that has both a default constructor and a parameterized constructor in Java:
Source code:
public class Person {
private String name; private int age; // Default constructor public Person() { name = "Unknown"; age = 0; } // Parameterized constructor public Person(String name, int age) { this.name = name; this.age = age; } // Getter methods public String getName() { return name; } public int getAge() { return age; } // Setter methods public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } }In this example, we have a class called Person
with two constructors - a default constructor and a parameterized constructor. The default constructor sets the name
field to "Unknown" and the age
field to 0. The parameterized constructor takes in two parameters - a name
of type String
and an age
of type int
. The this
keyword is used to refer to the current object's fields, and the parameters are used to set the values of the object's name
and age
fields.
The class also has getter and setter methods to access and modify the private fields of the class.
With this class, we can create objects of Person
using either the default constructor or the parameterized constructor:
// Creating an object using the default constructor Person p1 = new Person(); // Creating an object using the parameterized constructor Person p2 = new Person("John Doe", 30);
In the first example, p1
is created using the default constructor, and its name
and age
fields are set to "Unknown" and 0, respectively. In the second example, p2
is created using the parameterized constructor, and its name
and age
fields are set to "John Doe" and 30, respectively.
SORRY FOR THE INCONVINIENCE FROM THE NEXT BLOG ONWARDS YOU CAN DOWNLOADE THE SOURCE CODE.
Thanks for reading
please comment if any change needed*
Comments
Post a Comment