A (175)

(Tuis.) #1
CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces 137

Note An instance is a concrete object created from the blueprint of the class, with its own states or
unique data attributes. For example, you might have a (second) baby blue car instance that is traveling south
and is in third gear. (In the example, our first car instance is red, and is traveling north, in first gear.)

To illustrate this further, let’s construct a basic class for our car object example. To create a car class,
you use the Java keyword class, followed by your custom name for the new class you are writing,
and then curly brackets that will contain your Java code class definition, like so:


class Car {
// Java code definition for the car class will go in here. We will do this next!
}


The first thing that you usually put inside of a class (inside the curly {} brackets) is the data fields
(variables).


These variables will hold the states, or characteristics, of your Car object. In this case, you will have
six data fields, which will define the car’s current gear, current speed, current direction, fuel type,
color, and drive-train (two-wheel drive or four-wheel drive), as was specified in the basic diagram
shown earlier, in Figure 5-1.


To define a variable in Java, you must first declare its data type. An integer or int data type declares
a variable to be able to hold a whole (non-fractional) number. A String data type declares the
variable to hold a text value.


The next portion of the variable definition or “declaration” after the data type has been specified is
your custom variable name, which you will use to refer to that variable later on within your Java
programming logic. If you want to know technically what the Android OS is going to do with
these variable declarations, it is essentially going to set aside, or “allocate” an area in the system
hardware memory to hold this value for your application.


You can also (optionally) set a default, or starting, data value for your variable. This is done by using
the equal sign and a starting or default data value. The variable definition is ended once it reaches,
or is terminated with, a semicolon character. This is how the Android compiler in Eclipse, which
is reading or “parsing” your Java code, knows that each statement or “Java structure component
definition” is finished being defined.


Note Semicolons are used in programming languages to separate each code construct, or definition, from
the other code constructs within that same body of code (variable, method, interface, and so forth).
Free download pdf