Object Oriented Programming
Constructor in Java
A constructor is a special method that builds the object when a new object is created.
Syntax
modifier class className {
modifier className(inputParameters){
//set fields and run methods needed on instantiation here
}
}
Notes
There can be multiple constructors with a different number or types of input parameters. This is known as overloading (in fact, methods can be overloaded as well). This is useful if there are many fields within the class, and the user wants defaults set for these fields if not passed in during instantiation.
Often times, a constructor's input parameters will have the same variable name as the variables within the class. Member variables within the class can be referenced using the 'this' keyword.
Example
public class City {
string cityName; //fields
int population;
public City() { //constructor if no input parameters are provided
this.cityName = "No city name provided";
this.population = 0;
}
public City(String cityName) { //constructor if only a city name is provided
this.cityName = cityName; //this keyword distinguishes the cityName's
this.population = 0;
}
public City(String cityName, int population) { //constructor if both parameters provided
this.cityName = cityName;
this.population = population;
}
}