DALLASCAO.COM

Site of Cao Shouguang, English to Chinese translator

Learn java: Contructors vs methods


public class Car {

	/**Output: 
My car has 4 doors
Your car has 3 doors
Your car is driven by your wife
	 */
	String make;
	String model;
	int numDoors;
	// constructor, applying to all cars
	Car(String make, String model, int numDoors) {
		this.make = make;
		this.model = model;
		this.numDoors = numDoors;
	}
	//constructor set default numDoors to 4 
	Car(String make, String model) {
		this(make,model,4);
	}
	//method
	String drivenBy(String driver) {
		return driver;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub		
		Car yourCar = new Car("Mazda", "RX-8", 3);
		Car myCar = new Car("Toyota", "Camry"); // numDoors is 4 when this parameter is omitted
		System.out.println("My car has " + myCar.numDoors + " doors");
		System.out.println("Your car has " + yourCar.numDoors + " doors");
		System.out.println("Your car is driven by " + yourCar.drivenBy("your wife"));
	}

}

Constructors construct the class. They have to use the same name with the class. A method is more like a function that has a return value.

Leave a Comment