Writing Constructors
Introduction: 5.2.0
constructors
set intial values for an object’s instance variables- written after the instance variables and before methods
- typically public
- sidenote: not true for singleton design, something we use in robotics!
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
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.