Java Reference
In-Depth Information
The instance variables in Display 4.1 can be used just like any other variables. For
example, date1.month can be used just like any other variable of type String . The
instance variables date1.day and date1.year can be used just like any other variables
of type int . Thus, although the following is not in the spirit of the class definition, it is
legal and would compile:
date1.month = "Hello friend.";
More likely assignments to instance variables are given in the program
DateFirstTryDemo .
The class DateFirstTry has only one method, which is named writeOutput . We
reproduce the definition of the method here:
public void writeOutput()
{
Heading
Body
System.out.println(month + " " + day + ", " + year);
}
All method definitions belong to some class, and all method definitions are given
inside the definition of the class to which they belong. A method definition is divided
into two parts, a heading and a method body , as illustrated by the annotation on
the method definition. The word void means this is a method for performing an
action as opposed to producing a value. We will say more about method definitions
later in this chapter (including some indication of why the word void was chosen to
indicate an action). You have already been using methods from predefined classes.
The way you invoke a method from a class definition you write is the same as the
way you do it for a predefined class. For example, the following from the program
DateFirstTryDemo is an invocation of the method writeOutput with date1 as the
calling object:
heading
method body
date1.writeOutput();
This invocation is equivalent to execution of the method body. So, this invocation is
equivalent to
System.out.println(month + " " + day + ", " + year);
However, we need to say more about exactly how this is equivalent. If you simply
replace the method invocation with this System.out.println statement, you
will get a compiler error message. Note that within the definition for the method
writeOutput , the names of the instance variables are used without any calling
object. This is because the method will be invoked with different calling objects
at different times. When an instance variable is used in a method definition, it
is understood to be the instance variable of the calling object. So in the program
DateFirstTryDemo,
date1.writeOutput();
 
Search WWH ::




Custom Search