user2022068
user2022068

Reputation:

Java type casting and scope

I have two interfaces: MinServer and MaxServer. MaxServer extends 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

Upvotes: 0

Views: 210

Answers (3)

brso05
brso05

Reputation: 13222

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...

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180276

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. 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".

Upvotes: 0

DWilches
DWilches

Reputation: 23015

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.

If you change it like this:

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

then it will be correct.

Upvotes: 2

Related Questions