Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

super in static context

 
David Duran
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there anyway to reference a subclass's superclass using the "super" keyword within a static context?
For Example:
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi David,

Is there anyway to reference a subclass's superclass using the "super" keyword within a static context?

No, because super is a reference to an instantiated object which is non-static. If you call it from a static (class scope) context, which instance of super are you referring to? Even though the member you may be referring to is indeed static, how can you expect the compiler to resolve the reference to super?
Michael Morris
 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you thought about using a method to get the value of the subclass? The method could be called on any class that is a Supper.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually - yes.
If a sub-class has a static variable x that hides a variable x of the same name in the super class, preventing it from being inherited, then one of the acceptable syntax forms for getting at the super classes variable is
super.x;
This is exactly equivalent to using
Supper.x;
See the JLS: 8.3.3.1 Example: Hiding of Class Variables
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heck - even if you did NOT hide it in the sub-class and could legitamately use the simple variable name x you are still ALLOWED to use the super.x syntax it you choose.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Heck - even if you did NOT hide it in the sub-class and could legitamately use the simple variable name x you are still ALLOWED to use the super.x syntax it you choose.

But you still can't refer to super or this from a static context. I thought that was what the original question was all about, not member hiding.
You can do this :

But you can't do this:

Michael Morris
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Duh! Oh, that "from a static context" part :roll: . (Of course that IS what his example showed - sigh).
So you are correct - to do it you would need something not in a static context like:

[ March 04, 2003: Message edited by: Cindy Glass ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic