1class Other{
2 public Other(String message){
3 System.out.println(message);
4 }
5}
6
7class scratch{
8 public static void main(String[] args) {
9 Other method = new Other("Hey");
10 //prints Hey to the console
11 }
12}
1A constructor is a special method used to initialize objects in java.
2we use constructors to initialize all variables in the class
3when an object is created. As and when an object
4is created it is initialized automatically with the help of
5constructor in java.
6
7We have two types of constructors:
8Default Constructor
9Parameterized Constructor
10
11public classname(){
12}
13public classname(parameters list){
14}
1class Vehicle {
2
3 public int mYear;
4 public String mBrand;
5 public String mModel;
6 public int mMiles;
7 public int mPrice;
8
9 public Vehicle(int year, String brand, String model, int miles, int price) {
10 mYear = year;
11 mBrand = brand;
12 mModel = model;
13 mMiles = miles;
14 mPrice = price;
15 }
16
17 public boolean worthBuying(int maxPrice){
18 return (mPrice < maxPrice);
19 }
20
21 }
22
23
1A constructor in Java is a block of code similar to a method that's called when an instance of an object is created.