Published
- 3 min read
Constructor and Setter/Getter Methods

Constructor Methods
Constructors are special methods within a class that are called when an instance of the class is created. They typically set the initial attributes of that instance of an object, but do not themselves return any values. In most OOP languages, the new
keyword will automatically invoke the most appropriate constructor within the class it operates on.
A constructor method must have the same name as the class itself, and it is acceptable to have multiple constructors (called constructor overloading).
A Constructor may also take no arguments, which is referred to as a Default Constructor. This allows the developer to first create the object before injecting attributes into it. This can be useful in situations where the object must be created before any assignments can be made (such as simple validation like checking if the object exists).
Getter and Setter Methods
Getter and Setter methods are special methods of a class specifically to retrieve the values of private fields. Because these fields are not available to other classes and parts of the program, there needs to be some way for these fields to be able to interact with them.
These methods are generally made available in the corresponding Properties for these private variables. The compiler is able to recognize when a Getter or Setter is invoked by specific keywords in each language. An example would be something like
private string name = ""
public string Name {get ; set ; }
In the main program function, you can then simply do:
obj.Name = "Sean"
And because of the assignment operator, it will know to invoke the setter method. When you attempt to simply pass obj.Name
, then it will know it should simply invoke the getter method.
Object Methods
While not strictly related to the topic, I thought a word on when such practices are best utilized my be wise to mention.
Deciding when to make a new method and what scope it should belong to is generally a case by case decision, but it relies on a few factors you should consider:
- Does this method make sense to go here?
Say we have some class named
Player.cs
This is just a basic class with a constructor and some attributes set on instantiation, and has a simple method TakeDamage() that accepts an int value for the damage dealt to the Player and then reduces the private int Health by that amount.
If we wanted to add a new method GetPlayerName, it could go in the Player Class, sure. It sort of works, and for every player we’d have a way to access their name pretty easily, but is that the best fit for it?
In a lot of cases, yes, it is. Either that, or we’d just access the property directly without the use of an additional method.
- DRY and maintainable
Age old checklist. See if creating this method will reduce repetitive calls (like fitting nicely in a loop or being a good callback function or something similar).