java - instanceof 的罕见行为

标签 java class inheritance instanceof

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

"if ( commPort instanceof SerialPort )"

返回 true

"commPort" is CommPort class object

和 “SerialPort”是继承CommPort类的类

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

正确的例子是:

串行端口串行端口;

"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

关于java - instanceof 的罕见行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091121/

相关文章:

java - RecyclerView崩溃

java - 如何在 SNMP 中遍历 OID

java - 使用泛型编译错误

c++ - c++中没有虚函数的多重继承

java - 编译 Apache Thrift 生成的实现抽象类的 Java 类时出错

java - Tomcat 7 WAR 部署(Spring Boot)- 无法启动组件

php - NetBeans 中的 "No Suggestions"

c++ - 派生类如何访问基类的私有(private)数据成员?

c++ - 不允许定义一个类的多个实例

java - 为什么字段从父类打印,而方法从子类打印(Java)