wood burning stoves 2.0*
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
Author

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: }
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

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
sscce.org
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.....

HTH


<a href="http://faq.javaranch.com/java/UseCodeTags" target="_blank" rel="nofollow">Use Code Tags!!</a>
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Doubt in the code.
 
Similar Threads
plz help
plz help
why this error "casting "
Tips,oneliner Just before the SCJP Exam
Sub Class and super class