Java - Understanding constructors

by
Jeremy Canfield |
Updated: September 16 2022
| Java articles
Consider the following markup. In this example, there is a class called MyClass. Within the class, there is a constructor also called MyClass, because the name of the constructor must match the name of the class. Also, a constructor cannot be void (eg. public void MyClass). In this example, the constructor updates the "name" variable to have a value of John Doe. Generally speaking, constructors are used to update a variable to contain a value.
package my.pkg;
public class MyClass {
String name;
public MyClass() {
name = "John Doe";
}
}
As we can see, a constructor exists inside of a bean or class.
Did you find this article helpful?
If so, consider buying me a coffee over at