A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors do not have an explicit return type.
A constructor in Java is a special method used to initialize objects. The constructor is called when an object of a class is created.
Syntax:
class ClassName {
ClassName() {
}
}
Example
Create a constructor:
public class JavaApplication {
int x; // Create a class attribute
// Create a class constructor
public JavaApplication() {
x = 50; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
JavaApplication myObj = new JavaApplication(); // Create an object of class JavaApplication
System.out.println(myObj.x); // Print the value of x
}
}
Output:
50 |
Constructor Parameters
You can have as many parameters as you want:
Example:
public class JavaApplication {
int x; // Create a class attribute
// Create a class constructor
public JavaApplication(int y) {
x = y; // Set the initial value for the class attribute x
}
public static void main(String[] args) {
JavaApplication myObj = new JavaApplication(50); // Create an object of class JavaApplication
System.out.println(myObj.x); // Print the value of x
}
}
output:
50 |
thanks may this example will help you