JAVA Calling An Object
JAVA Calling An Object
You also use an object reference to invoke an object's method. You append the method's simple name to
the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses,
any arguments to the method. If the method does not require any arguments, use empty parentheses.
objectReference.methodName(argumentList);
Some methods, such as getArea(), return a value. For methods that return a value, you can use
the method invocation in expressions. You can assign the return value to a variable, use it to make
decisions, or control a loop. This code assigns the value returned by getArea() to the
variable areaOfRectangle:
Remember, invoking a method on a particular object is the same as sending a message to that object. In
this case, the object that getArea()is invoked on is the rectangle returned by the constructor.
It does not need to contain a return statement, but it may do so. In such a case, a return statement
can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
Any method that is not declared void must contain a return statement with a corresponding return
value, like this:
return returnValue;
The data type of the return value must match the method's declared return type; you can't return an integer
value from a method declared to return a boolean.
A method can also return a reference type.
For example, in a program to manipulate Bicycleobjects, we might have a method like this:
When a method uses a class name as its return type, such as whosFastest does, the class of the type of
the returned object must be either a subclass of, or the exact class of, the return type.
You can override a method and define it to return a subclass of the original method, like this:
This technique, called covariant return type, means that the return type is allowed to vary in the same
direction as the subclass.
Note: You also can use interface names as return types. In this case, the object returned must implement
the specified interface.