A (175)

(Tuis.) #1

144 CHAPTER 5: Introduction to Java: Objects, Methods, Classes, and Interfaces


// Invoking three methods on CarOne Car Object by using dot notation
carOne.shiftGears(3);
carOne.accelerateSpeed(15);
carOne.turnWheel("E");


// Invoking three methods on CarTwo Car Object by using dot notation
carTwo.shiftGears(2);
carTwo.applyBrake(10);
carTwo.turnWheel("W");
}


Upon launch or creation of our Android application, which is what the .onCreate( ) method is used
for, we now have instantiated and configured two Car objects. We have done this by using the Car( )
class constructor along with the Java new keyword, which creates a new Car object for us, using
the following Java code format:


Car carOne = new Car("carName", carSpeed, "carDirection", "carColor");


The syntax for doing this is very similar to what we used to declare our variables:


   Define the object type Car
 Give a name to our Car object (carOne) that we can reference in our class and
method code
 Set the carOne object equal to a new Car object definition using four “state”
value parameters (a String carName, an integer carSpeed, a String carDirection,
a String carColor)

It is also important to notice that I have put comments in the Java code by using two forward
slashes, which tells the Eclipse Java compiler to “ignore everything else on this line after these, as it
is a comment!”


To invoke our methods using our new Car objects requires the use of something called dot notation.
Once you have created and named a Java object, you can call methods off of it, by using the
following code construct:


objectName.methodName(parameter list variable);


So, to shift into third gear on the Car object named carOne, we would use this Java code statement:


carOne.shiftGears(3);


This “calls” or “invokes” the .shiftGears( ) method off of the carOne Car object, and “passes over” the
gear parameter, which contains an integer value of 3. This value is then placed into the newGear
variable, which is then utilized by the .shiftGears( ) method’s internal code.


So, as you can see in the final six lines of code in the public void onCreate( ) method, we set the
carOne Car object to third gear, using .shiftGears(3), accelerate it from 15 to 30 mph, by accelerating
by a value of 15, using .accelerateSpeed(15), and then turn east by using the .turnWheel() method
with a String value of "E" (the default direction is north, or "N").

Free download pdf