简体   繁体   English

Java类型转换和作用域

[英]Java type casting and scope

I have two interfaces: MinServer and MaxServer. 我有两个接口:MinServer和MaxServer。 MaxServer extends MinServer. MaxServer扩展了MinServer。 So, is the following code normal and right? 那么,以下代码正常吗?

MinServer server=foo.getUndefinedServer();
...code according to MinServer
if (isThisServerMax){
  server=(MaxServer)server;
...code according to MaxServer
}
...code according to MinServer

No, it is not correct. 不,这是不正确的。

At this point: 这一点:

server=(MaxServer)server
...code according to MaxServer

You are casting a MaxServer to a MinServer (which is OK) but then you assign the result of the casting to a MinServer ... so ehhm, you are in the same point where you started. 您正在将MaxServer强制转换为MinServer(可以),然后将强制转换的结果分配给MinServer ...嗯,您就在开始的同一点。

If you change it like this: 如果您这样更改:

MaxServer server2 = (MaxServer)server
...code according to MaxServer using server2

then it will be correct. 那将是正确的。

No. 没有。

If the isThisServerMax is a boolean variable that correctly indicates whether server 's class implements MaxServer , then everything actually shown will run without error. 如果isThisServerMax是一个boolean变量,可以正确指示server的类是否实现MaxServer ,则实际显示的所有内容都将正确运行。 However, nothing you present establishes a context wherein methods can be invoked on server that do not belong to interface MinServer , as I suppose is the intended meaning of "code according to MaxServer". 但是,您呈现的任何内容都无法建立一个上下文,在该上下文中可以在不属于接口MinServer server上调用方法,因为我想这是“根据MaxServer进行编码”的预期含义。

There is nothing wrong with the downcast you are doing. 您所做的垂头丧气没有错。 It will compile fine. 它将编译正常。 Just know that if it can't be downcasted it will throw a runtime exception that you should handle. 只是知道,如果不能对其进行向下转换,它将抛出您应处理的运行时异常。 If it is not actually a MaxServer then it will throw an error... 如果它实际上不是MaxServer,则会抛出错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM