Sams Teach Yourself C in 21 Days

(singke) #1
Working with Java Classes and Methods 727

BD5


Let’s look at SimpleClass.java first. Line 1 imports the Stringclass, necessary
because the class you are creating makes use of String. Line 3 is the class defin-
ition, indicating that this class does not inherit from any other class and that it has pub-
licvisibility. Lines 5 and 6 declare the two variables that are the class’s properties.
ClassBasicsDemo.java is a bit more complicated. Line 1 of course is the class definition,
and line 2 defines the mainmethod that is required in any Java stand-alone program. Line
4 declares a variable of type SimpleClass—in other words, a variable that can hold a ref-
erence to an instance of SimpleClass. Then, line 6 uses the newkeyword to actually cre-
ate an instance of SimpleClassand assign the reference to the variable MyClass. Lines
7 and 8 assign data to the object properties using the standard syntax objectname.prop-
ertyname. Finally, lines 9 through 12 display the property values on the screen.

ANALYSIS

You might be wondering why the program ClassBasicsDemo did not use the
include statement to reference the class SimpleClass. That’s because the
two files are part of the same Java project. If SimpleClasshad been com-
piled as part of a separate package, the include statement would be
required.

Note


Class Methods ....................................................................................................


Although some classes contain only properties, most classes contain one or more meth-
ods. A method is simply a Java function. It is a separate section of code that has a name,
can be passed arguments, and can return a value to the calling program. In Java, as in all
languages, methods (functions) are used to isolate sections of code that perform a spe-
cific task. The syntax for creating a method is
privacyKeyword type methodName (argument1, argument2, ...)
{
...
}
TheprivacyKeyworddetermines where the method can be called from. Use publicto
make the method callable from outside the class the method is in (this is what you’ll usu-
ally use). Use privateto restrict the method to being called by code within the class.
Thetypekeyword specifies the return type of the method—in other words, the type of
the data returned by the method to the caller. It can be an object type, such as String,or
one of Java’s primitive types.

40 448201x-Bonus5 8/13/02 11:23 AM Page 727

Free download pdf