Java Reference
In-Depth Information
of the notation and terminology used for classes. A
class
is the name for a type whose
values are objects.
Objects
are entities that store data and can take actions. For exam-
ple, objects of the class
String
store data consisting of strings of characters, such as
"Hello"
. The actions that an object can take are called
methods
. Most of the methods
for the class
String
return some value—that is, produce some value. For example, the
method
length()
returns the number of characters in a
String
object. So,
"Hello".length()
returns the integer
5
and this returned value can be stored in an
int
variable as follows:
class
object
method
int
n = "Hello".length();
As indicated by the example
"Hello".length()
, a method is called into action by
writing a name for the object followed by a dot followed by the method name with
parentheses. When you call a method into action, you are (or your code is) said to
invoke
the method or
call
the method, and the object before the dot is known as the
calling object
.
Although you can call a method with a constant object, as in
"Hello".length()
, it
is more common to use a variable as the calling object, as illustrated by the following:
method call
or method
invocation
calling object
String greeting = "Hello";
int
n = greeting.length();
Information needed for the method invocation is given in the parentheses. In some
cases, like the method
length
, no information is needed (other than the data in the
calling object) and the parentheses are empty. In other cases, which we see soon, there
is some information that must be provided inside the parentheses. The information in
parentheses is known as an
argument
(or arguments).
Invoking a method
is also sometimes called
sending a message
to the object. With
this view a message is sent to the object (by invoking a method) and in response the
object performs some action. For example, in response to the message
argument
sending a
message
greeting.length()
the object
greeting
answers with the value
5
.
All objects within a class have the same methods, but each object can have different
data. For example, the two
String
objects
"Hello"
and
"Good-Bye"
have different
data—that is, different strings of characters. However, they have the same methods.
Thus, since we know that the
String
object
"Hello"
has the method
length()
, we
know that the
String
object
"Good-Bye"
must also have the method
length()
.
You now have seen two kinds of types in Java: primitive types and class types. The
main difference you have seen between these two kinds of types is that classes have
methods and primitive types do not have methods. We will later see more differences
between classes and primitive types. A smaller difference between primitive types and
class types is that all the primitive types are spelled using only lowercase letters but, by
convention, class types are spelled with their first letter in uppercase, as in
String
.