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.
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, but not every Sample1 is a Sample2 (all Cats are Animals, but not all Animals are CAts).
Hello james, when you say "ref to a Sample1", your talking about st's Ref Var Type or st's Object type? Because if we omit line 14 st=s1 and then run the o/p is met2. So I'm guessing it's based on Object type, i.e after omitting line 14, Sample1 st = s2 makes st's Object type as Sample2 and hence the casting is successful. Am I understanding correct?
P.S: met2() has a error that SOP should contain string "met2"
It can be very confusing to talk about var's and object's types, so I'm going to stick to the proper Java terminology. st is a reference variable that can only refer to objects of type Sample1 or any subclass of Sample1. (Sample2) st creates a reference that can only refer to objects of type Sample2 (or any subclass of Sample2).
At compile time the compiler can't determine whether that will be valid or not, so it's checked at runtime. At runtime it discovers that st is referring to a Sample1, so that is not a valid value for a (Sample2) st reference. Hence the exception.
Without line 14 it discovers that st refers to a Sample2, so the cast is OK.