开发者

what would be the output?

开发者 https://www.devze.com 2023-01-03 03:00 出处:网络
Please explain me below situation What would be the output? interface A{} class B implements A{} class C extends B{}

Please explain me below situation What would be the output?


interface A{}
class B implements A{}
class C extends B{}
class D extends C{}
class E extends D{
public static void main(String args[]){
C c = new C(开发者_运维百科);
B b = c;
A a = (E)c;
a = (B)c;
c = (C)(B)c;
}
}


Being completely strict, that' won't compile because in line 4 you type Class instead of class

Class D extends C{}

And later you define twice a and c

C c = new C(); // once
B b = c;
A a = (E)c;    // once a
A a = (B)c;    // twice c
C c = (C)(B)c; // twice

Now assuming those were typos the output would be ClassCastException because c can't be casted to E.

When you perform a cast is like you were saying: "I'm the programmer and I know this is a..." ____(put your class here) And the compiler will allow you compile.

But if in runtime the instance is not really a ____ ( an E in this case, which is not ) then it will throw ClassCastException.

The program won't fail with A a = ( B ) c; because c is an instance of C which is a subclass of B.

You can say that, C is a B. To understand it better think on the following declaration:

class Employee extends Object {
}

Every Employee is an Object so the cast will succeed, actually is it so clear that it will succeed that you don't even need to put the cast operator ().

 Employee e = new Employee();
 Object o = ( Object ) e; // or much better:
 Object o2 = e; // no cast needed when assigning to superclass. 

But not necessarily an Object is an Employee.

 Object o = ....
 Employee e = ( Employee ) o; // will fail if o was not created as an Employee. 

That's why A a = ( E ) c; fail, because, the reference c was not created as an E

I hope that helps.


ClassCastException at A a = (E)c;


Without actually trying it, I'll go out on a limb and say that this line will cause two compiler errors:

C c = (C)(B)c;
  1. You're declaring the variable 'c' twice.
  2. You can't cast from B to C.

And if you actually put a double cast like that into a real project, then you deserve to get your ass kicked.


The object c is created as a new C. Since C extends B it is no problem assigning it to a variable of type B. However C knows nothing about E, so you can't cast here. You can only do this with super-classes. Since A is the absolute top level it is fine to assign any objects of the types you have defined to it.


I think there's no output. Because you didn't tell it where the entry point is.

If you did specify the main class as D E, there would still be no output since all those classes extend an empty class.

0

精彩评论

暂无评论...
验证码 换一张
取 消