Introduction: 5.2.0

  • constructors set intial values for an object’s instance variables
    • written after the instance variables and before methods
    • typically public
    • public ClassName()
    • they don’t have a return type
    • can intake parameters, which help to initialize values!
    • Must be the same name as the class!
  • Classes usually have more than one constructor
    • has one with no parameters
    • has one which takes in parameters
    • this is known as overloading the constructor
public class House {
    String address;
    Color paintColor;

    public House(String add, Color pColor) {
        address = add;
        paintColor = pColor;
    }

    public House() {
        this("123 street street", Color.orange);  
        // this calls the above constructor instead of repeating a bunch of code
    }
}
  • if there are no constructors, java provides a default constructor
    • Instance variables are set to default values
    • objects are set to null!
    • Java will not do this if you explicitly define a constructor

Objects as parameters

  • when you pass object references as parameters, these variables become aliases to the original object
    • They can modify it!
    • you need to copy the object into the parameters of a new object to avoid modifying this reference

Summary: 5.2.2

  • Constructors are used to set the initial state of an object
  • When no constructor is provides, java provides a no-argument default constructor
  • Constructor parameters are local variables to the constructor