public class MyClass {//this is an example of a class with a non default constructor
private int number = 0;
public MyClass() {
}
public MyClass(int theNumber) {//this is the constructor
//acces modifiers+constructor name(it needs to be the same as the class name)+parameters
this.number = theNumber;
}
}
A constructor is a special method used to initialize objects in java.
we use constructors to initialize all variables in the class
when an object is created. As and when an object
is created it is initialized automatically with the help of
constructor in java.
We have two types of constructors:
Default Constructor
Parameterized Constructor
public classname(){
}
public classname(parameters list){
}
import java.util.*;
class Examplec{
public static void main(String[]args){
Scanner input=new Scanner(System.in);
Car c1=new Car();
c1.setName("Rover");
c1.setColor("black");
c1.setPrice("450,000");
System.out.println(c1.getName());
System.out.println(c1.getColor());
System.out.println(c1.getPrice()+"
");
//constructor
Car c2=new Car("BMW","black","100,000,000");
System.out.println();
}
}
class Car{
private String name;
private String color;
private String price;
//with parameters
public Car(String name,String color,String price){
this.name=name;
this.color=color;
this.price=price;
System.out.println(name);
System.out.println(color);
System.out.println(price);
}
public Car(){}
public void setName(String name){
this.name=name;
}
public void setColor(String color){
this.color=color;
}
public void setPrice(String price){
this.price=price;
}
public String getName(){
return name;
}
public String getColor(){
return color;
}
public String getPrice(){
return price;
}
}