Java Reference
In-Depth Information
continued
For all the other classes, methods, and variables you've seen so far, however, I've
avoided talking about access modifiers and just supplied no modifier. So what do
these modifiers actually do? You will read an in‐depth discussion about them in
Chapter 8, but for now, just be aware that access‐level modifiers determine which
other classes can use the class, method, or variable the modifier relates to. When no
modifier is supplied, as with these examples, Java will make the class, method, or
variable accessible to the class itself (luckily, this should always be the case, other-
wise the method or variable would not be of much use), and also to classes living in
the same package . So far, you have not dealt with packages, so that each class you
created in Eclipse lives in the so‐called “default package,” and each class can access
the variables from another class.
This default behavior goes against the encapsulation ideology of object‐oriented
programming, and it is a little bit of a pity that this is chosen as the default behav-
ior in Java. For now, you can afford to be a little sloppy, but you will notice that
you start to encapsulate more and more data by wrapping methods around them
when you define classes, until you arrive at Chapter 7, where you will be introduced
to access modifiers for real—as to prevent direct variable access. One question you
might have at this point is whether it ever makes sense to make a member variable
directly accessible (by supplying no modifier or by making it public ). The answer
is very rarely. In most cases, it pays off to keep data hidden within the object and
use methods as guards around it. Only for very simple “data structure” classes
(such as a Point class with x and y variables) is it okay to allow direct access.
The previous Try It Out mentioned that it is possible to add more than one main method to your
Java projects (although they should be contained in different classes, of course). You might be
wondering how Java decides which main method to run when running your programs directly
(without going through Eclipse). The answer is that Java will either rely on a special description
file, or on the users passing the class name they want to run the main method from explicitly.
If you're interested in knowing more, you can explore the following Try It Out. The Try It Out
will also show you how to utilize the main method's single String[] argument, which we've
ignored so far.
Working with Program arguments 
try it out
This exercise demonstrates how to use program arguments.
1.
Create a new Eclipse project and add a single Program class with the following main method:
class Program {
public static void main(String[] args) {
p("You have supplied "+args.length+" arguments...");
Search WWH ::




Custom Search