Tags

,

— Used to initialise the variables for an object created for a class, constructor is called as soon as an object is created using “new” keyword.

— Constructors make it easy to initialise ALL variables of an object in one go

— Constructor has same name as the class.

— Has no return type.

— If you do not define a constructor, a no-argument constructor is created by default.

— Constructor Overloading: Creating Constructors with different arguments. Used when you need to initialize a class in different ways , for e.g. you may not want to use all class variables for all initialised objects.

— “this” keyword is used to let Java compiler know that the variable followed by “this” is the class variable. It’s convenient to use the class variables as the constructor arguments  and then use “this” keyword for assigning values.


public class vehicle {

	int wheels = 4;
	String model;
	String transmission;
	String colour;
	int price;
	
	public vehicle() { // Constructor without argument
			
	}
   // Constructor with arguments
	public vehicle(int carwheels, String carmodel, int carprice) { 
		wheels = carwheels;
		model = carmodel;
		price = carprice;
	}
	
	// Another constructor with arguments - parameterised constructor
	public vehicle(int wheels, String model, String transmission, int price){
		this.wheels = wheels;
		this.model = model;
		this.transmission = transmission;
		this.price = price;
		
	}
	
	public void printvehicledetails(){
		
		System.out.println("Model of vehicle is  " + model);
		System.out.println("Price of vehicle is  " + price);
		System.out.println("Number of wheels in vehicle is  " + wheels);
	}

public static void main(String[] args){
	
	vehicle myCar = new vehicle(4, "Hyundai", 24000);
	
	myCar.printvehicledetails();
	
	vehicle myTruck = new vehicle(6, "Mazda", "automatic" , 300000);
	myTruck.printvehicledetails();
	
}
}


Advertisements