CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces 143
you would do this by simply creating a longer parameter list for the constructor method call. This
revised Car( ) constructor method’s Java code structure would look something like the following:
class Car {
String name;
int speed;
int gear;
int drivetrain;
String direction;
String color;
String fuel;
public Car (String carName, int carSpeed, String carDirection, String carColor) {
name = carName;
speed = carSpeed;
gear = 1;
drivetrain = 4;
direction = carDirection;
color = carColor;
fuel = "Gas";
}
}
It is important to note that this Car( ) constructor method will not do anything at all until you use it to
instantiate an “instance” of the Car object. An instance is just what it sounds like it is; the Android OS
will allocate system memory space to hold each particular instance of any Java object created by its
class’s constructor method.
A constructor method must be called or invoked in conjunction with the Java “new” keyword, which
we will cover next. The new keyword creates a new object in a new area of system memory, so it’s
keyword appropriate!
Next, let’s look at how you would create new Car objects in your current MainActivity.java class
Java code.
Instantiating Objects: The Java “new” Keyword
To create an instance of an object, you instantiate it. Here’s what it would look like if you added
this code to the .onCreate( ) method of your current Android application. This shows the creation
of two Car objects, as well as how you would use these Car objects along with dot notation to call
the methods that would operate upon them. Refer to Figure 3-8 in Chapter 3 to see this bootstrap
.onCreate() method code for the Android app.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Two forward slashes allow you to insert comments into your code
// Create new Car Objects using the Car() constructor method
Car carOne = new Car("carWon", 20, "S", "Blue");
Car carTwo = new Car("carTwoon", 10, "N", "Green");