Java Exercise – On Constructor with Solution

Java exercises on constructor with solutions.

EXERCISE-1:

Answer the following questions in brief.

  1. When a class constructor gets called?
  2. If you create 5 objects of a class, then how many time constructors will be called?
  3. When you write a constructor, what return type do you write in constructor declaration?
  4. Why do you use constructor?

EXERCISE-2:

Write a constructor in the Car class given below that initializes the brand class field with the string “Ford”.

Call the getBrand() method in the main method of the Sample class  and store the value of the brand in a variable, and print the value.

class Car {

	String brand;
	
	//your constructor here
	
	public String getBrand() {
		return brand;
	}

	void run() {
		System.out.println("Car is running...");
	}
}

public class Sample {
	
	public static void main(String[] args) {

				Car ford = new Car();			
	}
}


SOLUTION-1:

Answers:

1) When we create an object of the class.

2) Constructor will be called 5 times on crating 5 objects of the class. On every object creation a constructor gets called.

3) No need to write a return type in a constructor declaration.

4) Constructor is used to initialise the class fields (class member variables) with default values / initial values.

SOLUTION-2

class Car {

	String brand;
	
	//your constructor here
	public Car(){
		this.brand ="Ford";
	}
	
	public String getBrand() {
		return brand;
	}

	void run() {
		System.out.println("Car is running...");
	}
}

public class Sample {
	
	public static void main(String[] args) {

				Car ford = new Car();
				String brand = ford.getBrand();
				System.out.println(brand);
	}
}

Output:

Ford

Related Posts