C# Exercise – On Constructor with Solution

C# 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”.

all 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() {
		Console.WriteLine("Car is running...");
	}
}

class Sample {
	
	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 creating 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 initialize 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() {
            Console.WriteLine("Car is running...");
	}
    }

    class Sample
    {

        public static void Main(String[] args) {

				Car ford = new Car();
				String brand = ford.getBrand();
                Console.WriteLine(brand);
	}
    }

Output:

Ford

Related Posts