[java] instanceof

来源:互联网 发布:java 流程引擎 编辑:程序博客网 时间:2024/05/21 21:03

1. 父类的实例调用instanceof只是父类的实例

2. 子类的实例调用instanceof即是父类的实例又是子类的实例

3. 示例:

package p_java;public class Bag {protected void inUse(){System.out.println("put into anything");}}

package p_java;public class Wallet extends Bag {protected void inUse(){System.out.println("put into money");}}

/** *  */package p_java;import org.hamcrest.core.IsInstanceOf;public class Test {/** * @param args */public static void main(String[] args) {Bag bag =new Bag();Wallet wallet = new Wallet();if(bag instanceof Bag){System.out.println("bag is the instanceof Bag ");}else{System.out.println("bag is not the instanceof Bag ");}if(bag instanceof Wallet){System.out.println("bag is the instanceof Wallet ");}else{System.out.println("bag is not the instanceof Wallet ");}if(wallet instanceof Bag){System.out.println("wallet is the instanceof Bag ");}else{System.out.println("wallet is not the instanceof Bag ");}if(wallet instanceof Wallet){System.out.println("wallet is the instanceof Wallet ");}else{System.out.println("wallet is not the instanceof Wallet ");}}}

4. 结果

bag is the instanceof Bag
bag is not the instanceof Wallet
wallet is the instanceof Bag
wallet is the instanceof Wallet


0 0
原创粉丝点击