CLASS CONSTRUCTOR IN JAVA PROGRAMMING
CLASS CONSTRUCTOR IN JAVA
In Java, constructor works like a method and it initializes object during its creation i.e when object is created using new
keyword. Its syntax is similar to the syntax of creating method and secondly it must matches the name of the class. The third requirement is that it can't have any return type. You can't create two duplicate constructors in the same class in java but you can create the constructors with different signatures like: one constructor can't have any argument passed to it while other can have argument passed to it. The following is the basic example illustrating constructor in Java.
package Lesson1;
public class Bike {
String model_name;
int mileage;
Bike(){
model_name="KTM RC 390";
mileage=26;
}
Bike(String model, int speed){
model_name=model;
mileage=speed;
}
}
package Lesson1;
public class ClassConstructor {
public static void main(String[] args) {
Bike Duke= new Bike();
System.out.println(Duke.mileage);
Bike Apache = new Bike("RTR 200 CC", 28);
System.out.println(Apache.model_name);
}
}
Here you can see I have created two constructors- one with no argument passed to it and the other has argument passed to it. The output is as follow: