Game Development Reference
In-Depth Information
The reason that a Java object is declared in this way, using the class name, the
name of the object you are constructing, the Java new keyword , and the class's con-
structor method name (and parameters, if any) in a single Java statement terminated
with a semicolon, is because a Java object is an instance of a Java class.
Let's take a look at, for example, the Button object creation from line 20 of your
current Java code. Here, via the part of the Java statement on the left-hand side of the
equals operator, you are telling the Java language compiler that you want to create a
Button object named btn , using the JavaFX Button class as the object blueprint. This
declares the Button class (object type) and gives it a unique name.
The first part of creating the object is thus called the object declaration . The
second part of creating your Java object is called the object instantiation , and this part
of the object creation process, seen on the right-hand side of the equals operator, in-
volves a constructor method and the Java new keyword.
To instantiate a Java object, you invoke the Java new keyword, in conjunction with
an object constructor method call. Because this takes place on the right-hand side of the
equals operator, the result of the object instantiation is placed in the declared object,
which is on the left-hand side of the Java statement. As you will see a bit later in the
chapter, when I discuss operators (see the section “Java Operators: Manipulating Data
in the Application”), this is what an equals operator does, and a useful operator it is.
This completes the process of declaring (class name), naming (object name), cre-
ating (using a new keyword), configuring (using a constructor method), and loading
(using the equals operator) your very own custom Java object.
It is important to note that the declaration and instancing parts of this process can
be coded using separate lines of Java code as well. For instance, the Button object in-
stantiation (see Figure 3-2 , l. 20) could be coded as follows:
Button btn;
btn = new Button();
This is significant, because coding an object creation in this way allows you to de-
clare an object at the top of your class, where each of the methods inside the class that
use or access these objects can see the object. In Java, unless declared otherwise, using
modifiers, an object or data field is only visible inside the Java programming construct
(class or method) in which it is declared.
If you declare an object inside your class, and therefore outside all the methods
contained in the class, then all the methods in your class can access (use) that object.
Similarly, anything declared inside a method is local to that method and is only visible
to other members of that method (Java statements inside the method scope delimiters).
Search WWH ::




Custom Search