Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Instantiating hidden classes (static)

 
mario de simone
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does the 'greeting' method from 'XSuper' get executed and the 'name' method from 'XSub'. I thought they should be from 'XSub', and the result should be "Hello, Dick". however, it is actually "Goodnight, Dick".

class XSuper {
static String greeting() { return "Goodnight"; }
String name() { return "Richard"; }
}
class YSub extends XSuper {
static String greeting() { return "Hello"; }
String name() { return "Dick"; }
}
public class Test1 {
public static void main(String[] args) {
XSuper s = new YSub();
System.out.println(s.greeting() + ", " + s.name());
}
}
 
Fred Hosch
Author
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods don't get overriden, they get hidden. the method
greeting() in YSub hides, but does not override, the method
greeting() in XSuper.
there is no overriding, so resolution of the invocation
s.greeting() depends on the compile-time type class of s,
which is XSuper. It does not matter that s happens to refer
to a YSub at run-time.
------------------
Fred Hosch
Author of:
An Introduction to Software Construction with Java
 
mario de simone
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your help Fred. I really appreciate it.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic