Next: Defining a class. Up: Objects review. Previous: Definitions.
This is simply declaring a variable of the given type.
There is no difference between this statement and a statement like ``int i.'' Here, we are creating a variable called rob to be a name for a Robot object.Robot rob;
We haven't actually made it be a name for any particular object yet. In fact, rob will hold null.
Or we could create a name for a DrawableFrame object.
DrawableFrame window;
To assign an object to a name, we'll want to create the object.
Here, we're changing what object the rob name is naming. In this case, the object we're making it be a name for is a new Robot object created on the same line.window = new DrawableFrame(); rob = new Robot(window, 100, 100);
The same object can have multiple names. For example, the following code would create a second name bert for rob.
Robot bert; bert = rob;
The new keyword is used when you want to create an instance. The way it works is as follows.
Each object has several methods which specify what we can ask of that object. For example, a Robot object might have the following methods. (This is how they might be described in the documentation.)
To tell a Robot object to accomplish one of these behaviors, we would give the name of a Robot, followed by a period and the method name, with a set of parentheses. Any parameters required by the method would go inside the parentheses.
Here, we have told rob to move forward 50 pixels. Then we told rob to turn left. (Note that when we told rob to turn left, we still had to include the parentheses, even though we had no parameter values to give him.)rob.moveForward(50); rob.turnLeft();
Many methods can return a value - this would be the object's response to the request. You can tell in the documentation that it returns something when there is a type name other than void listed before the method name. For example, the getY() method returns an int. We can put such a method call anywhere we can place an expression. For example, we might put the return value into a variable.
Here, we've asked rob for his y-coordinate, and then we've told rob to move that far forward. We could combine these into a single line to accomplish the same thing.int y; y = rob.getY(); rob.moveForward(y);
rob.moveForward(rob.getY());
Next: Defining a class. Up: Objects review. Previous: Definitions.