Java How To Write A Constructor
Writing a constructor in Java is easy. Constructors are used to initialize an instance of a class. They can also be used to handle initial parameters. The constructor for a class has the same name as the class and does not have a return value. If a return value is specified it will not be treated as an actual constructor and will not be called when creating an instance of a class.
The most basic syntax looks like this:
public class MyClass{
MyClass(){
}
Here is an example of a simple constructor that initializes a variable.
import java.util.*;
public class Test1 {
public int x;
public Test1(){ // constructor
x = 1234; // initialize variable
}
public static void main( String[] args ){
Test1 t = new Test1();
System.out.println( t.x );
}
}
You can also pass a parameter to a constructor like this.
public Test1(int a){ // constructor
x = a; // initialize variable
}
If the parameter has the same name as the class attribute that you want to set you can refer to it using the “this” keyword like this.
public Test1(int x){ // constructor
this.x = x; // initialize variable
}