Constuctors
- Java constructors are special types of methods that are used to initialize an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.
Rules for Creating Java Constructors
The name of the constructors must be the same as the class name.
Java constructors do not have a return type. Even do not use void as a return type.
There can be multiple constructors in the same class, this concept is known as constructor overloading.
Types of Java Constructors
Default Constructor
- If you do not create any constructor in the class, Java provides a default constructor that initializes the object.
public class Main {
int num1;
int num2;
public static void main(String[] args) {
Main obj_x = new Main();
// Printing the values
System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}
OUTPUT:
num1 : 0
num2 : 0
No-Argument Constructor
- As the name specifies, the No-argument constructor does not accept any argument. By using the No-Args constructor you can initialize the class data members and perform various activities that you want on object creation.
public class Main {
int num1;
int num2;
Main() {
num1 = -1;
num2 = -1;
}
public static void main(String[] args) {
Main obj_x = new Main();
// Printing the values
System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
}
}
OUTPUT:
num1 : -1
num2 : -1
Parameterized Constructor
- A constructor with one or more arguments is called a parameterized constructor.
public class Main {
int num1;
int num2;
Main(int a, int b) {
num1 = a;
num2 = b;
}
public static void main(String[] args) {
Main obj_x = new Main(10, 20);
System.out.println("obj_x");
System.out.println("num1 : " + obj_x.num1);
System.out.println("num2 : " + obj_x.num2);
OUTPUT:
obj_x
num1 : 10
num2 : 20
Top comments (0)