I'm new to "CodeRanch".
So exactly don't know the correct standards for asking or posting anything.
But I need some help with mentioned problem in image.
As shown in image how many of those fragments
-will throw ClassCastException at runtime
-will be Executed successfully
and how is that possible?
Thanks in advance.
In this question there is 3 class and 1 interface———
AccOrdin To question Car is a parent class and FancyCar and SuperFancyCar is a child of car showing single level inheritance.
Breakable is interface which is only implemented by fancyCar and SuperFancyCar but not by Car.
Now in main method we are calling static print method in which we are passing instance of FancyCar.
And when we call print method we pass instance to Car car ( Car type object car reference holding child object which is FancyCar)
We can say that
Car car = new FancyCar
So we can say that Car can hold only it’s implemented object and can acces only car methods because you cannot acces child specific method using parent reference
And also Car not implements interface Breakable so you cannot acces it’s breakSmoothly method too.
Now come to the fragment part after having all information
In F1 will throw classcast Exception (because while casting there must be parent to child relationship or same ) so there is Breakable which is a interface and new FancyCar is a child of car so there is no parent child relationship or same kind . If it is FancyCar instead of Breakable it would have been compile successfully .
As given in F5 fragment so it will compile.
In F2 again same ClassCastException will throw because SuperFancyCar is child saying FancyCar is a SuperFancyCar which is not possible but opposit is true.
In F3 again same case as in F2
In F4 there is no classcastexception but compiler error because we are trying to access child method ( turn() belongs to SuperFancyCar so I already stated above parent class can’t access child method FancyCar is parent to SuperFancyCar )
F6 will compile successfully because accelerate method belongs to car so no issues
In F7 again compilation error car is parent class and turn() is a method of SuperFancyCar .
In F8 car doesn’t implement interface Breakable so it can’t have breakSmoothly method so again compilation error
So conclusion is F1,F2,F3 will throw ClassCastException
F4,F7,F8 will not compile
F5 and F6 will be executed successfully