(^78) | Java Syntax and Semantics, Classes, and Objects
becomes much easier with practice. That’s why it’s a good idea to practice first with an ap-
plication such as PrintName, where mistakes don’t matter—unlike in homework programming
assignments!
2.4 Classes and Methods
We’ve now seen how to write an application class that has just the required method,main.
This kind of coding resembles the process of coding programs that were written in older
languages that lacked support for object-oriented programming. Of course, as problem com-
plexity grows, the number of declarations and executable statements also grows. Eventually,
applications may become so immense that it is nearly impossible to maintain them. To avoid
this complexity, we can break the problem up into classes that are small enough to be eas-
ily understood and that we can test and debug independently. In this section we see how to
declare classes other than an application class, and methods other than main.
User Classes
All of the syntax that we’ve seen for declaring application classes applies for declaring non-
application classes as well. The only differences are that the latter classes do not contain a
mainmethod, and for now we won’t use the publicmodifier. Java permits an application to
have just one public class. In a later chapter we will see how to create our own packages, like
java.io; with such packages, we can bundle together a collection of public classes. Within a
single application, however, the only class that can be public is the one that contains main.
As an example, let’s consider creating a class called Namethat provides the responsibili-
ties needed by the PrintNameapplication. Then we can simplify main, gaining some experience
with object-oriented programming style along the way. What would we like Nameto do? It
would be nice to have it get a name from the user, store the name internally, and provide
methods that return the name in the different formats.
From our prior experience (looking for things that are familiar), we know that the class
needs fields to hold the parts of the name. Here’s what we now know we need:
className
{
String first; // Person’s first name
String last; // Person’s last name
String middle; // Person’s middle initial
}
The class should have a method for each of its responsibilities. In this case, we need a
method to get a name from the user, another to return the name in the first format, and a
third to return the name in the second format. It looks as though we’re ready to take a closer
look at writing methods.