Constructor overloading in Java

Constructor overloading in Java

Constructor overloading in Java allows you to define multiple constructors within a class, each with a different parameter list. This enables you to create instances of the class with various combinations of arguments. Constructor overloading is a form of method overloading that is specific to constructors.

Here's an example of constructor overloading in Java:

public class Person { private String name; private int age; // Constructor with no arguments public Person() { this.name = "Unknown"; this.age = 0; } // Constructor with name parameter public Person(String name) { this.name = name; this.age = 0; } // Constructor with name and age parameters public Person(String name, int age) { this.name = name; this.age = age; } // Getter methods to retrieve the name and age public String getName() { return name; } public int getAge() { return age; } public static void main(String[] args) { // Creating instances of the Person class using different constructors Person person1 = new Person(); Person person2 = new Person("Alice"); Person person3 = new Person("Bob", 30); // Retrieving and printing the details of each person System.out.println("Person 1: Name=" + person1.getName() + ", Age=" + person1.getAge()); System.out.println("Person 2: Name=" + person2.getName() + ", Age=" + person2.getAge()); System.out.println("Person 3: Name=" + person3.getName() + ", Age=" + person3.getAge()); } } 

In this example:

  • The Person class has three constructors: one with no arguments, one with a name parameter, and one with both name and age parameters. These constructors allow you to create Person objects with different sets of attributes.

  • The getter methods getName() and getAge() are used to retrieve the name and age of a Person object.

  • In the main method, we create three Person objects using the different constructors, and then print their details.

Constructor overloading is a useful technique in Java for providing flexibility when creating objects of a class. It allows you to initialize objects with varying sets of initial values based on your application's requirements.


More Tags

radix azure-hdinsight drupal-modules ngrx-store geckodriver spring-java-config running-count compare angular-tree-component spring-cloud-gateway

More Java Questions

More Chemical reactions Calculators

More Livestock Calculators

More Entertainment Anecdotes Calculators

More Statistics Calculators