Compiles fine. But at runtime it gives ClassCastException. My doubt is that why is it so even though st which is of type Sample1 gets casted to Sample2 and generates exception even though Sample2 IS-A Sample1.
Jump to Post
st is a copy of s1, which is a ref to a Sample1. You then try to cast that so Sample2, which is invalid.
The relevant rule is that you can cast a subclass to it superclass, but not vice-versa.
This is because every Sample2 is, by definition a Sample1, …
All 4 Replies
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.