what is constructor in java
In Java, a constructor is a special type of method used to initialize objects when they are created.
It is called automatically when an instance of a class is created using the new keyword.
Basic program of constructor in java:
class Bike{
String make;
String model;
int year ;
String color;
int gear ;
Bike(String make,String model,int year,String color,int gear)
{
this.make=make;
this.model=model;
this.year=year;
this.color=color;
this.gear=gear;
}
void GetBike(){
System.out.println("make:"+make);
System.out.println("model:"+model);
}
void GetStructure(){
System.out.println("year:"+year);
}
void GetDep(){
System.out.println("color:"+color);
System.out.println("gear:"+gear);
}
public static void main(String[]args){
Bike b1=new Bike("cramy","royal enfield",2020,"red",5);
b1.GetBike();
b1.GetStructure();
b1.GetDep();
}
}
Output:
Top comments (0)