instanceof 的罕见行为

A rare behavior of instanceof

我正在尝试理解本教程的代码: Java serial 特别是:

"if ( commPort instanceof SerialPort )"

那个return是真的

"commPort" is CommPort class object

和 "SerialPort" 是继承 CommPort class

的 class

commPort 怎么可能是 SerialPort 的实例 class。

正确的是,例如:

串口串口;

"if ( serialPort instanceof CommPort )"

还是我错了? 谢谢...

how is possible that commPort could be instance of SerialPort class.

你说

"SerialPort" is a class that inherits of CommPort class

所以你可以

CommPort commPort = new SerialPort();
if (commPort instanceof SerialPort) // true.

但是如果你这样写

CommPort commPort = new ParallelPort();
if (commPort instanceof SerialPort) // false