Constructor Java Program

A constructor in Java is a special type of method that is used to initialize objects. It has the same name as the class and is used to create an instance of the class. In this article, we will discuss how to write a Java program that uses a constructor.

To create a constructor in Java, we need to define a method with the same name as the class. The constructor does not have a return type, not even void. It is responsible for initializing the object’s state. Here is an example of a constructor that initializes a person object with a name and age:

public class Person {
    String name;
    int age;

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

    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);
        System.out.println("Name: " + person.name);
        System.out.println("Age: " + person.age);
    }
}

Let’s break down this code line by line.

  • The first line defines a public class named Person.
  • The next two lines declare two instance variables, name and age.
  • We define a constructor for the Person class that takes two parameters, name and age. Inside the constructor, we use the this keyword to refer to the instance variables of the object being created and assign the passed values to them.
  • Inside the main() method, we create a new Person object named person and pass in the values “John Doe” and 30 to the constructor.
  • We output the name and age of the person object using the System.out.println() method.

When we run this program, the output will be:

Name: John Doe
Age: 30

This program demonstrates how to create a constructor in Java and use it to initialize an object’s state. Constructors are an important concept in object-oriented programming and are used extensively in Java programs. By understanding the basics of Java syntax and constructors, you can create more complex programs that work with a wide variety of objects.