0 votes
in JAVA by
What is a constructor in java?

1 Answer

0 votes
by

What is a constructor in java?

"A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

Example

Create a constructor:

// Create a MyClass class

public class MyClass {

  int x;  // Create a class attribute

  // Create a class constructor for the MyClass class

  public MyClass() {

    x = 5;  // Set the initial value for the class attribute x

  }

  public static void main(String[] args) {

    MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the constructor)

    System.out.println(myObj.x); // Print the value of x

  }

}

// Outputs 5

🔗Reference: stackoverflow.com

🔗Source: Java Interview Questions and Answers

Related questions

+1 vote
asked Jan 24, 2020 in JAVA by rahuljain1
0 votes
asked Feb 8, 2021 in JAVA by SakshiSharma
...