Casting between an interface submar and a superclass when a superclass does not implement an interface, but a subclass

In the following code

abstract class Vehicle { }
class Car extends Vehicle implements LandMover { }
interface LandMover { }
     Car porsche=new Car();
     LandMover lmv;
     lmv = porsche;
     Vehicle vec = (Vehicle)lmv;

Should there be a compiler error in the 4th line, since there is no connection between the class vehicle and the LandMover interface? and if not, what could be the reason. Thanks!

+4
source share
7 answers

The compiler checks if a possible connection exists, and there is one:

A LandMovermay be Carthat, in turn, IS-A Vehicle. Since you promise that this conversion is fine using explicit casts, the compiler is happy.

+6
source

No, since

    LandMover lmv = porsche;

LandMover, "" "LandMover". , "" (: "" "" ).

+1

Vehicle . , , , , -, Vehicle

0

, . lmv = porsche; ,

public class Car extends Vehicle implements LandMover {

    public static void main(String args[]){

        LandMover car = new Car();
    }
}

A Car LandMover, . .

Vehicle vec = (Vehicle)lmv;

, LandMover (), , . .

, , , vec, ( Car, Car) .

, , , , ( ), .

0

. , , "LandMover" . , , , "java.lang.String" "Vehicle", , .

0

Car extends Vehicle

&

Car implements LandMover

Vehicle vec = (Vehicle)lmv; ( ), lmv, LandMover , , CAN be Car ( Car implements LandMover). Car extends Vehicle .

to confirm , try commenting out the code as follows

        //Car porsche=new Car();
         LandMover lmv;
         //lmv= porsche;
         Vehicle vec = (Vehicle)lmv; //Compiler error

Here the compiler is sure that it lmv CANNOT be Vehicle, and therefore a flag error.

0
source

there will be an error because the abstract class cannot be created to get more information about this post

-1
source

All Articles