static field in a class hierarchy

G

Gael

Hi,

I have an abstract class A, and two subclasses B and C.
Those classes have a static field F declared in abstract A class.

If I got it correctly, F is unique, and therefore has the same value
in the 3 classes A, B and C. Is that correct?

Then, is there a way to have a F field that could have different
values in A, B and C classes, but still a unique value for all
instances of A class, a second unique value for all instances of B
class, and a third unique value for all instances of C class?

What's the best practise here?

Thanx for advising...
Gaël
 
A

Adam

I have an abstract class A, and two subclasses B and C.
Those classes have a static field F declared in abstract A class.

If I got it correctly, F is unique, and therefore has the same value
in the 3 classes A, B and C. Is that correct? True.

Then, is there a way to have a F field that could have different
values in A, B and C classes, but still a unique value for all
instances of A class, a second unique value for all instances of B
class, and a third unique value for all instances of C class?
Only by having different static instances in all classes.
And to avoid errors I would make them private:

class A
{
private static F f = new F();//same for all A objects
}

class B extends A
{
private static F f = new F();//same for all B objects, diffrent than A.f
}

etc.
Inheritance is not important here (from the aspect of those statics).
What's the best practise here?
I don't know, more details needed.

Adam
 
A

Andy Fish

I don't know, more details needed.

I think the best practise would be to have a method getF() that you override
in each subclass rather than accessing the static variable directly

imagine you had a variable declared to be of class A but actually it would
be a B or C. AFAIK If you tried to access the field you would get A's value
which kind of breaks the whole polymorphism idea.

or imagine you decided to later subclass C and make a new class D.
references to F in C.java would be to C's F but references in D.java would
be to D's F.

Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,906
Latest member
SkinfixSkintag

Latest Threads

Top