T
TGOS
If I'd design a new language tomorrow (OO of course) and I'd
leave out static variables, do you think it would be fatal?
Can anyone provide me an example, where a certain problem
can't be solved without the existence of static variables in
Java? I challange you and claim "No such example exists".
Prove me wrong ;-)
The prototype example for static variable is "Count the
number of instances of a class". Well, I can do this without
static variables (and I will even write my code as very
clean OO):
class InstanceCounter {
private int instances;
public InstanceCounter() {
instances = 0;
}
public void addInstance() { instances++; }
public void removeInstance() { instances--; }
public int getNumberOfInstances() { return instances; }
}
class Foo {
private InstanceCounter ic;
public Foo(InstanceCounter ic) {
this.ic = ic;
ic.addInstance();
}
public void finalize() {
ic.removeInstance();
}
}
public class StaticTest {
public static void main(String[] args) {
InstanceCounter ic = new InstanceCounter();
Foo f1 = new Foo(ic);
Foo f2 = new Foo(ic);
Foo f3 = new Foo(ic);
System.out.println("There are " +
ic.getNumberOfInstances() +
" instances of Foo.");
f1 = null;
System.gc();
System.out.println("There are " +
ic.getNumberOfInstances() +
" instances of Foo.");
}
}
Output:
There are 3 instances of Foo.
There are 2 instances of Foo.
Instance counter, you see
leave out static variables, do you think it would be fatal?
Can anyone provide me an example, where a certain problem
can't be solved without the existence of static variables in
Java? I challange you and claim "No such example exists".
Prove me wrong ;-)
The prototype example for static variable is "Count the
number of instances of a class". Well, I can do this without
static variables (and I will even write my code as very
clean OO):
class InstanceCounter {
private int instances;
public InstanceCounter() {
instances = 0;
}
public void addInstance() { instances++; }
public void removeInstance() { instances--; }
public int getNumberOfInstances() { return instances; }
}
class Foo {
private InstanceCounter ic;
public Foo(InstanceCounter ic) {
this.ic = ic;
ic.addInstance();
}
public void finalize() {
ic.removeInstance();
}
}
public class StaticTest {
public static void main(String[] args) {
InstanceCounter ic = new InstanceCounter();
Foo f1 = new Foo(ic);
Foo f2 = new Foo(ic);
Foo f3 = new Foo(ic);
System.out.println("There are " +
ic.getNumberOfInstances() +
" instances of Foo.");
f1 = null;
System.gc();
System.out.println("There are " +
ic.getNumberOfInstances() +
" instances of Foo.");
}
}
Output:
There are 3 instances of Foo.
There are 2 instances of Foo.
Instance counter, you see