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