File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Doubt in the code. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt in the code." Watch "Doubt in the code." New topic

Doubt in the code.

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Show method in Test class");
6: }
7: }
9: public class Q2 extends Test
10: {
11: static void show()
12: {
13: System.out.println("Show method in Q2 class");
14: }
15: public static void main(String[] args)
16: {
17: Test t = new Test();
19: Q2 q = new Q2();
22: t = q;
25: q = t;
27: }
28: }

There is a compilation error at line 25, but i am not able to understand the reason.
marc weber

Joined: Aug 31, 2004
Posts: 11343

Q2 extends Test, so it's always true that an instance of Q2 IS-A Test. But an instance of Test is not always a Q2.

So assigning t = q (an upcast) is always safe. But assigning q = t (a downcast) is not always safe, so an explicit cast is required to avoid a compilation error.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Tom Johnson
Ranch Hand

Joined: May 11, 2005
Posts: 142
Hi, Just a comment or two....firstly, you should not access static methods using an instance reference, you should use the class reference. Secondly, you cannot override static methods (you may redefine them but the polymorphic behaviour you get with instance methods will not be present). Based on your code you you posted it looks like you would be expecting.....


<a href="" target="_blank" rel="nofollow">Use Code Tags!!</a>
I agree. Here's the link:
subject: Doubt in the code.
It's not a secret anymore!