instanceof and getClass()
2016-01-09 16:29
162 查看
instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.
getClass() == … tests whether the types are identical.
is a String
However, applying instanceof on a null reference variable returns false. For example, the following if statement returns false.
false
Since a subclass ‘is a’ type of its superclass, the following if statement, where Child is a subclass of Parent, returns true.
true
getClass() == … tests whether the types are identical.
public class MainClass { public static void main(String[] a) { String s = "Hello"; if (s instanceof java.lang.String) { System.out.println("is a String"); } } }
is a String
However, applying instanceof on a null reference variable returns false. For example, the following if statement returns false.
public class MainClass { public static void main(String[] a) { String s = null; if (s instanceof java.lang.String) { System.out.println("true"); } else { System.out.println("false"); } } }
false
Since a subclass ‘is a’ type of its superclass, the following if statement, where Child is a subclass of Parent, returns true.
class Parent { public Parent() { } } class Child extends Parent { public Child() { super(); } } public class MainClass { public static void main(String[] a) { Child child = new Child(); if (child instanceof Parent) { System.out.println("true"); } } }
true
相关文章推荐
- 由浅入深讲解Javascript继承机制与simple-inheritance源码分析
- Inheritance vs. Composition in Java
- 模板继承【粗翻译】
- Symbian 基础总结 --类类型
- 继承实例
- [CS193P] 第二堂課摘要及心得筆記
- Bad Smells in Code
- 设计模式理解
- C++ inheritance
- C++ 私有继承 VS Composition
- python 多继承(2)
- why overridden methods?
- Using FINAL with Data Member
- 我在翻译《Thinking in Java》(二)
- chapter 18 & 19 context
- java面试的一些试题
- C++之Access Label, Inheritance, and Friend
- Patterns Of Enterprise Application Architecture读书笔记
- 代码大全学习-9
- 代码大全学习-21-表驱动方法(Table-Driven Methods)