What do you mean by Constructor?

Java Programming Language >   Class, Object and Methods in java >   Application of OOP  

Short Question

820


Answer:

Constructor gets invoked when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.

A constructor in Java is a special type of method that is used to initialize objects of a class. It has the same name as the class and is called when an object of the class is created. A constructor can take arguments and can perform any initialization that is required for the object. The constructor is called automatically and is not invoked explicitly. The purpose of a constructor is to provide a convenient way to initialize objects with a specific set of values or properties.

Here is an example of a Java class with a constructor:


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

   // Constructor
   public Person(String name, int age) {
      this.name = name;
      this.age = 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;
   }
}

In this example, the Person class has a constructor that takes two arguments, name and age. The constructor initializes the instance variables name and age with the values passed as arguments. To create an object of the Person class, you can use the following code:


Person person = new Person("John Doe", 30);

In this code, the new keyword calls the constructor, and the arguments "John Doe" and 30 are passed to it. The constructor then initializes the name and age instance variables with these values.


This Particular section is dedicated to Question & Answer only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.