wood burning stoves
The moose likes Beginning Java and the fly likes plz help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "plz help" Watch "plz help" New topic

plz help

kashif sohail

Joined: Dec 04, 2000
Posts: 29
public class Q2 extends Test
static void show()
System.out.println("Show method in Q2 class");
public static void main(String[] args)
Test t = new Test();
Q2 q = new Q2();

t = q; //what happens here
t.show(); // which method called and why
q =(Q2) t; // why explicit cast
class Test
static void show()
System.out.println("Show method in Test class");
plz any body tells me the reason and explaination
Rob Acraman
Ranch Hand

Joined: Dec 03, 2000
Posts: 89
The reason you're not getting what you I think you're expecting to get is because of that little word "static". You've just discovered that static methods can't be overridden.
So, what's happening is:
t = q;
The reference in q is copied into t, so t and q are now both pointing to the same object in memory. Note that no casting is required here, since you're "upcasting" - ie. assigning a sub-type to a super-type, which is allowed (like myAnimal = dog).
Since Test's show() method is static, Java doesn't look any further down the inheritance tree since it can't be overwritten.
So, what's output is the "Test class" message.
q = (Q2)t;
Cast is needed since you're now "downcasting". OK, we "know" this instance of t is a Q2, but that counts for nothing with the compiler, since at runtime an instance of t may reference ANY sub-type of t (like saying myDog = someAnimal
Since show() is defined for Q2, Java doesn't need to go back up the inheritance tree - it can call the method direct.

Hope this helps
I agree. Here's the link: http://aspose.com/file-tools
subject: plz help
jQuery in Action, 3rd edition