my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on inheritance from Dan's exam Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on inheritance from Dan Watch "Question on inheritance from Dan New topic

Question on inheritance from Dan's exam

geeta rai
Ranch Hand

Joined: Sep 18, 2003
Posts: 48
class P {
static void printS1(){System.out.print("P.printS1 ");}
void printS2() {System.out.print("P.printS2 ");}
void printS1S2(){printS1();printS2();}
class Q extends P {
static void printS1(){System.out.print("Q.printS1 ");}
void printS2(){System.out.print("Q.printS2 ");}
public static void main(String[] args) {
new Q().printS1S2();
For the code above, the answer is
Prints: P.printS1 Q.printS2
The explaination says that If the method called is a static member of the class where the invocation expression occurs, then that is the implementation of the method that is invoked at run-time regardless of the run-time type of the object but the method printS1S2()is also a part of the class Q which inherits it from class P so shouldn't the method printS1() of class Q be called and the answer should be Q.printS1 Q.printS2?
Pls help me understand.
Dan Chisholm
Ranch Hand

Joined: Jul 02, 2002
Posts: 1865
Thank you for using my exam.
Your question come up frequently here at the Ranch. If you search on printS1S2 you will find lots of threads. (There's a search option near the top of the page.) Here's the most recent thread.

Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="" target="_blank" rel="nofollow">Try my mock exam.</a>
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
void printS1S2(){printS1();printS2();}
I sometimes wonder whether this is a valid way to explain why the rule is what it is:
In Java, class methods are bound at compile-time (static binding) and instance methods are bound at run-time (dynamic binding).
At compile-time, the method invocation printS1 is bound to the implementation printS1 in class P.
At run-time, the method invocation printS2 is chosen by the dynamic lookup process and bound to the implementation printS2 in class Q of the object.
geeta rai
Ranch Hand

Joined: Sep 18, 2003
Posts: 48
Thanks Dan and Marlene Miller for your help.
Mohit Goyal
Ranch Hand

Joined: Nov 09, 2003
Posts: 65
If u have a superclass and a subclass both having the same method and both marked static, then Polymorphism will not apply as in ur example because the static methods are not overriden but if the two methods r not static then the subclass method is overriding the superclass method and polymorphism will apply
I agree. Here's the link:
subject: Question on inheritance from Dan's exam
It's not a secret anymore!