Write a program in Java to develop overloaded constructor. Also develop the copy constructor to create a new object with the state of the existing object.

 here's an example Java program that demonstrates overloading constructors and a copy constructor:

Create a Person.java file and write this code in it.

public class Person {
    private String name;
    private int age;

    // Default constructor
    public Person() {
        this.name = "";
        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;
    }

    // Copy constructor
    public Person(Person person) {
        this.name = person.name;
        this.age = person.age;
    }

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public static void main(String[] args) {
        // Create a new Person object using the default constructor
        Person person1 = new Person();
        System.out.println("Person 1: " + person1.getName() + ", " + person1.getAge());

        // Create a new Person object using the name constructor
        Person person2 = new Person("Alice");
        System.out.println("Person 2: " + person2.getName() + ", " + person2.getAge());

        // Create a new Person object using the name and age constructor
        Person person3 = new Person("Bob", 30);
        System.out.println("Person 3: " + person3.getName() + ", " + person3.getAge());

        // Create a new Person object using the copy constructor
        Person person4 = new Person(person3);
        System.out.println("Person 4: " + person4.getName() + ", " + person4.getAge());
    }
}

In this example, we have a Person class with a default constructor and two overloaded constructors that take different combinations of name and age parameters. We also have a copy constructor that takes a Person object as a parameter and creates a new Person object with the same state.


In the main() method, we create four Person objects using the various constructors and print their details to the console. We can see that the copy constructor successfully creates a new Person object with the same state as an existing object.

Comments