Hi Carsten.
public class Counter extends .... {
public Counter() {
super(...);
}
private void updateCounter() {
count += 1;
}
public static int count = 1;
}
class AnotherClass extends ... {
public AnotherClass()
super(...);
}
Counter counter = new Counter();
counter.updateCounter();
This should the job.
Warm Regards
Darko Topolsek
> public class Counter extends .... {
> public Counter() {
[quoted text clipped - 4 lines]
> count += 1;
> }
Shouldn't this be public? How else can it be accessed from the
outside? Or did i miss some trick? :)
> [...]
Thanks for responding, but this doesn't quite do the trick. I think i
have to elaborate on what i want. From what i wrote previously, i
don't think it came out clearly.
I have a package, foo, containing the Counter class. Now i have a
class, A, which does: import foo.Counter;
A has a main method, which starts an instance of itself, wrapped in a
Thread. The Thread works as a ticker, counting the shared object
Counter up one.
Now i start another instance of A, from another shell. Since this does
the exact same thiing as the first A, it also imports foo.Counter.
What i want is for the second instance to start counting from where
the first instance was at when the second was started.
An example printout would be like this:
(Start A1, first instance of A, with java A)
A1: count: 1
A1: count: 2
A1: count: 3
(start A2, second instance of B, in another shell, with java A)
A2: count: 4
A1: count: 5
A2: count: 6
A1: count: 7
And so on...
From what i tried, A2 just starts counting from 1, and A1 just keeps
counting.
Any suggestions on how to crack this one? :)
- Carsten H. Pedersen
Oliver Wong - 23 Dec 2005 18:58 GMT
> Thanks for responding, but this doesn't quite do the trick. I think i have
> to elaborate on what i want. From what i wrote previously, i don't think
[quoted text clipped - 30 lines]
>
> Any suggestions on how to crack this one? :)
Your example is completely different from the explanation of your first
post, and completely different from your explanation in this post. I will
ignore both explanations and assume what you want is what the example shows.
In that case, you want to use the Singleton design pattern.
public class SingletonCounter {
private static final SingletonCounter soleInstance = new
SingletonCounter();
private SingleCounter() {
//Private constructor to prevent instantiation.
}
private int value = 1;
public getNextValue() {
return this.value++;
}
public static SingletonCounter getInstance() {
return soleInstance;
}
}
- Oliver