Search Interview Questions | More than 3000 questions in repository. There are more than 900 unanswered questions. Click here and help us by providing the answer. Have a video suggestion. Click Correct / Improve and please let us know. |
|
| ||||
Interview Questions and Answers for 'ClassCastException' - 2 question(s) found - Order By Newest | ||||
| ||||
Ans. As we only downcast class in the hierarchy, The ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance. | ||||
Help us improve. Please let us know the company, where you were asked this question : | ||||
Like Discuss Correct / Improve  java   oops   class casting   classcastexception   exception   error Asked in 4 Companies intermediate   frequent | ||||
Try 2 Question(s) Test | ||||
Related Questions | ||||
In which cases isn't instanceof operator a bad practice? | ||||
Invoking start twice on same thread leads to .. | ||||
| ||||
Ans. To avoid ClassCastException. Though the following code will compile fine but will result in ClassCastException during runtime. Fruit fruit = new Apple(); Banana banana = Banana(fruit); // ClassCastException This code will not give compile time error as Banana and Fruit are related as Banana either extends or implement Fruit, So downcasting is acceptable. With this code we assume that the Fruit handler will have the Apple object at that point, violating which the code will throw the exception. This exception can be avoided by following code. Fruit fruit = new Apple(); if(fruit instanceOf Banana){ Banana banana = Banana(fruit); // ClassCastException } | ||||
Help us improve. Please let us know the company, where you were asked this question : | ||||
Like Discuss Correct / Improve  java   instanceof   classcastexception   runtime exceptions  instanceOf operator | ||||
Try 2 Question(s) Test | ||||
Related Questions | ||||