constructor in java

In Java, a constructor is a special method that is used to create objects of a class. It has the same name as the class and no return type. When an object of a class is created, the constructor is automatically called to initialize the object.

Here’s an example of a simple constructor in Java:

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

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30);
        System.out.println(person1.getName()); // output: John
        System.out.println(person1.getAge()); // output: 30
    }
}

In this example, we have defined a Person class with a constructor that takes two parameters (name and age) and initializes the instance variables with those values. We can then create an object of the Person class by calling the constructor with the desired values. In this case, we create a new Person object called person1 with the name “John” and age 30.

Constructors can also be overloaded, meaning that a class can have multiple constructors with different parameter lists. Here’s an example:

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

    public Person() {
        name = "Unknown";
        age = 0;
    }

    public Person(String name) {
        this.name = name;
        age = 0;
    }

    public Person(int age) {
        name = "Unknown";
        this.age = age;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person();
        Person person2 = new Person("John");
        Person person3 = new Person(30);
        Person person4 = new Person("John", 30);

        System.out.println(person1.getName()); // output: Unknown
        System.out.println(person1.getAge()); // output: 0

        System.out.println(person2.getName()); // output: John
        System.out.println(person2.getAge()); // output: 0

        System.out.println(person3.getName()); // output: Unknown
        System.out.println(person3.getAge()); // output: 30

        System.out.println(person4.getName()); // output: John
        System.out.println(person4.getAge()); // output: 30
    }
}

In this example, we have defined four different constructors for the Person class, each with a different parameter list. We can then create objects of the Person class using any of these constructors, depending on the values we want to initialize the object with.

Share