I would like to get some help for the below question I found in Enthuware exam:
The answer is Line 2.
But I have a query here. Once a is assigned to b then its points to the b object. And in line 3 b=a,therfore b must simply point to the B object only. How can a ClassCastException be generated here?
As far as I know ClassCastException is a RuntimeException, the exam question is about compilation failure. Also you are mentioning "line 3 b=a", but that's not line 3, it's line 2. So not sure if this is related to the original exam question or if it's a doubt of your own
I don't feel that a ClassCastException must be generated.
Because at Line 1 if a=b, then when line 2 runs, b=a literally means that b s pointing again to its own B object because a is already pointing to the same in Line 2.
I feel that the code must run fine. But the answer is not that.
I want to know the flow of the program.
Explanation would be appreciated.
Have a look at this Java Tutorial. It's about inheritance and you definitely have to take a close look at the section "Casting Objects". I'm quite certain it will clear your doubts and you'll be able to answer your question yourself.
It might be easier to understand if you use more intuitive classes, rather than A and B.
Now, should that final line be valid? At that point animal could be referencing a Cat, a Dog, a Mouse, a plain Animal etc. Can you guarantee that it is safe to assign it to a Cat reference? No. So the compiler won't allow it.
If you used a cast:
Now you're overriding the compiler, telling it "trust me, it's a Cat". The compiler will allow it, but then you'll get a ClassCastException at runtime if it's not actually true.
Joined: May 17, 2013
A subclass reference cannot refer to a superclass object. That would give a compiler error. But in line 1 a=b.... That means A class reference points to the B class.
So when b=a, at that time a is already pointing to the B object. So indirectly b points to its own object.
Maybe if line 1 was removed, then I could have understood that there would be a compiler error on line 2. If I m wrong then how and how does line 1 and 2 work?
You normally don't catch/handle runtime exceptions. You have to prevent a runtime exception from happening (if possible) and in most cases it is possible (e.g. adding a null check, checking the length of an array or a list,...)
Let's take a look at a method that converts all of the characters of a given string to lower case:
But that could result in a NullPointerException when calling toLowerCase(null);, so instead of catching and handling this runtime exception we prevent this exception from happening like this:
Now it's up to you for the bonus question! Consider the code snippet below. Implement the getB() method (and that's the only thing you can do) in such a way that this little program has no compilation errors and when you run the program also no runtime exceptions are thrown.