Which is a method that is called when a new instance of a class is created?

Now that we can create both classes and custom methods, let's explore a special type of method called a constructor. We can use constructors to DRY up our code and make the process of instantiating new objects much quicker.


A constructor is a method that is called when a new instance of a class is created. Any information regarding the initial setup of a new object can be included in a constructor.

Writing Constructor Methods

Let's walk through adding a constructor to our Car class together:

...

public class Car
{
  public string MakeModel;
  public int Price;
  public int Miles;

  //New constructor code below.
  public Car(string makeModel, int price, int miles)
  {
    MakeModel = makeModel;
    Price = price;
    Miles = miles;
  }

  public bool WorthBuying(int maxPrice)
  {
    return (Price <= maxPrice);
  }
}

...

Constructors look a lot like other methods. Our constructor can take multiple parameters and also has an access modifier that we've set to public. Each of these parameters correspond to the fields a Car object should have, including an int value to represent its price, a

Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
0 containing a Car object's make, and so on.

When we call our constructor, we will pass in arguments for a Car's

Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
3,
Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
4, and
Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
5. A Car will be instantiated with the fields set to the arguments we've passed in. Note that the object's fields are in PascalCase while the constructor method's parameters are lowerCamelCase.

Our constructor method will also return an object of the class type it belongs to — in this case, our constructor will return an instance of Car.

Calling Constructor Methods

Constructors create new instances of a class when the

Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
8 keyword is used.
Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
8 denotes that we're creating a new instance of this class:

Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
  • Just like every other variable, it needs a type declaration. That's why the name of our custom class is the first element in this line of code.

  • It also has a name like any other variable. We're calling ours

    Car secondCar = new Car("1981 Ford Pinto", 200, 36000);
    
    0.

  • The word Car is included again after the

    Car firstCar = new Car("1980 Yugo Koral", 700, 56000);
    
    8 keyword because this is also the name of our constructor. It's best practice to name the constructor after the class it's called on.

  • Finally, we include the three arguments required by our constructor. They denote the make/model, price, and mileage of this car.

When our dealership gets another Car to sell, we can create another instance of this class, with different details:

Car secondCar = new Car("1981 Ford Pinto", 200, 36000);

Let's use our new constructor in the command line interface of our car dealership application.

We can refactor this area of our program:

...

public class Program
{
  public static void Main()
  {
    Car volkswagen = new Car();
    volkswagen.MakeModel = "1974 Volkswagen Thing";
    volkswagen.Price = 1100;
    volkswagen.Miles = 368792;

    Car yugo = new Car();
    yugo.MakeModel = "1980 Yugo Koral";
    yugo.Price = 700;
    yugo.Miles = 56000;

    Car ford = new Car();
    ford.MakeModel = "1988 Ford Country Squire";
    ford.Price = 1400;
    ford.Miles = 239001;

    Car amc = new Car();
    amc.MakeModel = "1976 AMC Pacer";
    amc.Price = 400;
    amc.Miles = 198000;

  ...
...

We will use our new constructor instead:

...

public class Program
{
  public static void Main()
  {
    Car volkswagen = new Car("1974 Volkswagen Thing", 1100, 368792);
    Car yugo = new Car("1980 Yugo Koral", 700, 56000);
    Car ford = new Car("1988 Ford Country Squire", 1400, 239001);
    Car amc = new Car("1976 AMC Pacer", 400, 198000);
  ...
...

The entire updated file should look like this:

using System;
using System.Collections.Generic;

public class Car
{
  public string MakeModel;
  public int Price;
  public int Miles;

  public Car(string makeModel, int price, int miles)
  {
    MakeModel = makeModel;
    Price = price;
    Miles = miles;
  }

  public bool WorthBuying(int maxPrice)
  {
    return (Price <= maxPrice);
  }
}

public class Program
{
  public static void Main()
  {
    Car volkswagen = new Car("1974 Volkswagen Thing", 1100, 368792);
    Car yugo = new Car("1980 Yugo Koral", 700, 56000);
    Car ford = new Car("1988 Ford Country Squire", 1400, 239001);
    Car amc = new Car("1976 AMC Pacer", 400, 198000);

    List Cars = new List() { volkswagen, yugo, ford, amc };

    Console.WriteLine("Enter maximum price: ");
    string stringMaxPrice = Console.ReadLine();
    int maxPrice = int.Parse(stringMaxPrice);

    List CarsMatchingSearch = new List(0);

    foreach (Car automobile in Cars)
    {
      if (automobile.WorthBuying(maxPrice))
      {
        CarsMatchingSearch.Add(automobile);
      }
    }

    foreach(Car automobile in CarsMatchingSearch)
    {
      Console.WriteLine(automobile.MakeModel);
    }
  }
}

Constructors allow us to write cleaner and DRYer code. Moving forward, use constructor methods to create instances of custom classes in all your applications.

What is called when an instance of a class is created?

The creation of an instance is called instantiation. An object may be varied in a number of ways. Each realized variation of that object is an instance of its class. That is, it is a member of a given class that has specified values rather than variables.

Which method of a class is used for creating an instance of the class?

Using newInstance() Method of Class class It returns a newly created instance of the class represented by the object. It internally uses the newInstance() method of the Constructor class.

What method gets called when a class object is created?

The constructor method is a special method for creating and initializing an object created with a class . There can only be one special method with the name "constructor" in a class.