Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A QUESTION..

 
Jaya Murugan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI.

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();
t.show();
Q2 q = new Q2();
q.show();
t = q;
t.show();
q = (Q2)t;//1
q.show();
}
}
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.
regards
Jaya Murugan
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
Regards,
Manfred.
 
rajani adapa
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic