wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A QUESTION.. 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A QUESTION.." Watch "A QUESTION.." New topic


Jaya Murugan
Ranch Hand

Joined: Nov 18, 2000
Posts: 34

class Test
static void show() {
System.out.println("Show method in Test class");
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;
q = (Q2)t;//1
when i run this o/p is
prints "Show method in Test class"...1
"Show method in Q2 class".....2
"Show method in Test class"...3
"Show method in Q2 class".....4
actually i expected runtime exception at //1..
what im missing ? pls help.
Jaya Murugan
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
You had a Test t and a Q2 q. Then you put q into a Test variable, but it is really a Q2, so when you cast t back into a Q2 there was no problem.

"JavaRanch, where the deer and the Certified play" - David O'Meara
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Jaya,
Your method is static which means only one method per class not instance. Therefore, static methods behave the same as class variables: they can only be shadowed versus overridden. Your code proves this out!
t will always be a Test
q will always be a Q2
Therefore regardless of what was done before when I use t as the object I will be looking at the Test class. The same goes for q: no matter what I perform before it will always use the Q2 class method 'show'.
You can always assign a subclass to a superclass: t = q without compiler problems. Once we have done that we can also undo it: q = (Q2)t since we know t points to a Q2 instance (i.e., we just assigned it before!).
If your example had not used static methods you would have understood the output better because of overriding...
rajani adapa
Ranch Hand

Joined: Jan 24, 2001
Posts: 54
I think it is not that casting to super class will give a runtime error always.the runtime environment checks whether this conversion is legal or not.and so presents no error in this case.

Remove the static from the method and run it.
u r getting an output as
Show method in Test class
Show method in Q2 class
Show method in Q2 class
Show method in Q2 class.
but the expected output is

Show method in Test class
Show method in Q2 class
Show method in Q2 class
Show method in Test class.

I agree. Here's the link: http://aspose.com/file-tools
subject: A QUESTION..
It's not a secret anymore!