Reputation: 10 Tradesman
- Active Posts:
- 48 (0.02 per day)
- 17-March 09
- Profile Views:
- Last Active:
- Nov 22 2014 04:18 AM
- Dream Kudos:
Posts I've Made
Posted 17 Apr 2014This is one of those things that's not particularly intuitive, I'll give it that.
Broadly, you can treat static fields as not inherited - the definition of a static field requires that there be only one for the entire type, and all classes that inherit from type A are ultimately of type A. HOWEVER - say you have a class A with static int variable x and an inheriting class B, the JVM/compiler will let you get away with doing this:
B b = new B(); int test = b.x;
which looks for all the world like an instance variable. It isn't - the call to
b.x;is treated in exactly the same way as the static call
Good IDEs will give you a warning about this - something along the lines of 'static fields should be accessed in a static way' but it is only a warning, not an error. There are ways to finagle static variables into behaving similarly to instance variables, but it generally isn't a good idea to try it.
One more interesting oddity of this - it allows you to look like you're referencing null!
B b = null; int test = b.x;
Again, that will compile and run, fetching the value of the static field x from the type A - but it's downright ugly.
- Member Title:
- New D.I.C Head
- Age Unknown
- Birthday Unknown
Maynia hasn't added any friends yet.