What will happen if you attempt to compile and run the following code?
class Base {}class Sub extends Base {}class Sub2 extends Base {}public class CEx{ public static void main(String argv[]){Base b=new Base();Sub s=(Sub) b; }}
1) Compile and run without error
2) Compile time Exception
3) Runtime Exception
May the force of the Java be in all of us !!!
"I'm not back." - Bill Harding, Twister
May the force of the Java be in all of us !!!
Thanks,
Mathews
May the force of the Java be in all of us !!!
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
May the force of the Java be in all of us !!!
When assigning one object reference to another the general rule is that you can assign up the inheritance tree but not down. You can think of this as follows. If you assign an instance of Child to Base, Java knows what methods will be in the Child class. However a child may have additional methods to its base class. You can force the issue by using a cast operation.
May the force of the Java be in all of us !!!
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Human h = new Queen();
Queen q = (Queen)h;
h = new Thug();
q = (Queen)h; //ClassCastException
May the force of the Java be in all of us !!!
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
At compile time Queen q = (Queen)(new Human()); and Thug t = (Thug)(new Human()); are both allowed, but fail at runtime.
May the force of the Java be in all of us !!!
Queen q=(Queen) new Human();
will compile but will also give a runtime error, correct?
Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
May the force of the Java be in all of us !!!
May the force of the Java be in all of us !!!
I wasn't selected to go to mars. This tiny ad got in ahead of me:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|