bigbinc said:
silly question, can final classes be used like global classes that can
be accessed by other classes. I have done it, but It feels like I am
following bad programming practice.
I.E.
public final class x {
static int y;
x() { y = 3; }
public static void addY() {
y++;
}
} // end of class
and then if I call this in other functions
x.addY();
x.addY();
it does change y? is this worth doing?
"final" on a class means only that it can't be subclassed.
final class X ...
class Y extends X // compile-time error
I don't know what you mean by a "global" class. A public class is visible
and accessible to every other class in the system.
In your example, you have a class (called x) with a constructor, a static
variable and a static method. The constructor is used to make new instances
of the class. (Along with the "new" keyword.) "static" means that the
variable and the method are shared among all instances of the class. In
particular, for static methods, you do not need an instance to call the
method; all you do is put the class name instead.
Your lines:
x.addY();
x.addY();
do not operate on any particular instance; they call the static method
called addY in the class x. After these lines complete (assuming that they
are the first things that run after class x is loaded and initialized) the
variable y should hold the value 2.
I don't know what you're trying to accomplish, but this code is unlikely to
do anything useful.
In particular, as soon as you construct a new x:
new x();
The value of y goes to 3. (Because this is exactly what the constructor
says.)
Let's follow this up:
new x(); // y == 3
x.addY(); // y == 4
x.addY(); // y == 5
new x(); // y == 3
Is this what you intended?
-- Adam Maass