This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'm not real great at explaining this stuff, but I'll try anyway.
In object inheritance, you generally add to or change the methods and properties of the base class, but you do not actually remove any of them, so object type casting only works in one direction.
Consider; what if class Q2 contains methods that do not exist in class Test?
If you could assign q=t with or without first casting it to Q2, then you could also try to call a (nonexistent) Q2 method on an object that is really a Test object.
If you try to make the assignment without a cast, then you get a compile time error; the compiler says, "I got a Test object, but this assignment requires a Q2 object," assuming that you know that Q2 subclasses Test. But you say, "Okay, I'll just cast it to Q2" and it compiles.
Great, but now you have a runtime error, because you can't cast types up the inheritance hierarchy -- the parent class might not have all of the methods, etc that the child class has.
Philip Shanks, SCJP - Castro Valley, CA
My boss never outsources or has lay-offs, and He's always hiring. I work for Jesus! Prepare your resume!
We cannot assign base class object to derived class reference.Through casting also it is not possible. so, q=t cannot be done in any case. Regarding super, In derived class show() method we can write super.show() , but for that you have to remove static from your show method of both the classes because super cannot be used in a static method.
Joined: Oct 15, 2002
Originally posted by vats rao: i didnt get you exactly.as the statement at 25th line ie "q=t" is wrong how it can be made error free with casting does it like q=super(t)?if not whats the other way
This will allow the code to compile, but will result in a runtime error.