Constructors
Now that we know how to declare a class, how do we create a new object? That’s where a special method called a constructor comes in. The constructor of a class is always
public
and has the exact same name as the class. It can have no parameters (the default constructor), or one or more parameters depending on how much of the class you want to customize. It also has no return type.It’s generally good practice to have at least 2 constructors: the default constructor and a constructor with enough parameters to initialize all of the class’s instance variables (non-static fields). Here is an example of 2 constructors for the Person class:
/** Constructs a default Person object */ public Person() { name = ""; age = 0; address = ""; hungry = false; } /** * Constructs a Person object with a given name, * age, address, and hunger status * @param name name of person * @param age how old the person is, in years * @param address address of person * @param hungry whether the person is hungry or not */ public Person(String name, int age, String address, boolean hungry) { this.name = name; this.age = age; this.address = address; this.hungry = hungry; }
this
keyword - what does it mean? The this
keyword is an abstract way of referring to an object. It can be used to call an instance’s fields or methods. In the case of a constructor, it’s usually used to differentiate between the parameter names and the field itself. For example, in the code above, the value that is passed into the parameter name will be assigned to the name variable of this object. Without using the this
keyword, you’d simply be typing name = name
, which doesn’t make sense because you’re just assigning a variable to itself.Above each of the constructors is what is called a Javadoc comment, which is a special multi-line comment that is used to generate documentation for your code. It is completely optional, but is good practice to have. For more on Javadocs, see this website: https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html
Instantiation
To call a constructor to create a new object, you need to use the
new
keyword. The process of creating a new object is called instantiation, because you’re creating an instance (synonymous with object) of the class.Person myPerson = new Person(); // call constructor
Note how like any variable, when you declare a variable you need to declare the type. The type is simply the class name, whether it’s
Person
, String
, or something else.Next Section
12.4 Accessors and MutatorsCopyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.