Last modified: January 07, 2024
Constructors are specialized methods that initialize an object. This is typically the place to initialize your instance variables and execute any code needed before the object is used. There are two kinds of constructors.
Default constructor: A constructor with no parameters that initializes an object to default values.
Parameterized constructors: Constructors with parameters that initialize an object according to the values passed in through the parameter list.
Let's add both kinds to our Person class.
public class Person {
// Instance Variables - fields storing info about the state
// of an object (attributes/properties)
...
// Constructors - Specialized methods that set an object up
// and initialize instance variables
// Default constructor - no parameters ()
public Person() {
myAge = 17;
myHeight = 1.53;
isStudent = false;
myName = "Frances";
}
// parameterized constructor - with parameters (a, b, c, ...)
public Person(int age, double height, boolean student, String name) {
myAge = age;
myHeight = height;
isStudent = student;
myName = name;
}
// Remaining code not shown
}
A few things to notice:
(data_type var_name1, data_type var_name2, ...)