Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in the code.

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1: class Test
2: {
3: static void show()
4: {
5: System.out.println("Show method in Test class");
6: }
7: }
8:
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();
18: t.show();
19: Q2 q = new Q2();
20: q.show();
21:
22: t = q;
23: t.show();
24:
25: q = t;
26: q.show();
27: }
28: }


There is a compilation error at line 25, but i am not able to understand the reason.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.....

HTH
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic