Chapter 5 ■ a Java primer: introduCtion to Java ConCepts and prinCiples
Constuctor Methods: Turning a Java Class into a Java Object
There is one specialized type of Java method I’m going to cover in detail in this section of this chapter called
a constructor method. This is a special type of method that can be used to create (construct) Java objects,
which we will be covering a bit later in the chapter, after we cover all of the different types of Java syntax
and programming structures that can be used to create, define, and interface with these Java objects. Java
objects just happen to be the foundation of Object-Oriented Programming (OOP), so we will be taking a
look at constructor methods here; it is important to have an understanding of this before we cover the Java
object itself later in the chapter. Since we are covering methods in this section, this is the most logical place
to take a look at constructors, as constructor methods are sometimes called (for short) by veteran Java game
developers, which you are on your way to becoming.
Creating a Java Object: Invoking the Class Constructor Method
A Java class can contain a constructor method with the same name as the class and can be used to create
Java objects using that class. A constructor method uses its Java class as a blueprint to create an instance
of that class in system memory, which creates the Java object. A constructor method will always return a
Java object and thus does not use any of the other Java return types that other methods will typically use
(void, String, float, int, byte, etc.). We will be covering these Java return types later during the chapter. The
constructor method should be invoked by using the Java new keyword since you are creating a new Java
object.
You can see an example of this in the bootstrap JavaFX code shown in Figure 5-2, in line numbers 20, 28,
and 30. These lines are where the Button, StackPane, and Scene objects are created, respectively, by using
the following object declaration, naming, and creation Java code structure, as follows: