instanceof

2021/10/22 23:09:58

本文主要是介绍instanceof,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

instanceof

public class Person {
    public void run(){
        System.out.println("run");
    }
}
public class Stendyent extends Person{
    public void go(){
        System.out.println("go");
    }
}
public class Teacher extends Person{
}
public class AppLication {
    public static void main(String[] args) {
        //类型之间的转换:父(高)  子(低)
        Person s = new Stendyent();
        //将s对象强制转换为Stendyent类型就可以使用go方法,强制转换可能会丢失一些自己本来的方法
        ((Stendyent) s).go();
​
        /*Object object = new Stendyent();
        //System.out.println(x instanceof y);能不能编译通过主要看两者之间有没有父子关系
​
        //Object > Person > Stuendy
        System.out.println(object instanceof Stendyent);//true
        System.out.println(object instanceof Person);//true
        System.out.println(object instanceof Object);//true
        //Object > Person > Teacher
        System.out.println(object instanceof Teacher);//false
        //Object > String
        System.out.println(object instanceof String);//false
​
        System.out.println("==================");
​
        Person person = new Stendyent();
​
        System.out.println(person instanceof Stendyent);//true
        System.out.println(person instanceof Person);//true
        System.out.println(person instanceof Object);//true
        System.out.println(person instanceof Teacher);//false
        //System.out.println(person instanceof String);//编译器报错
​
        System.out.println("==================");
​
        Stendyent stendyent = new Stendyent();
​
        System.out.println(stendyent instanceof Stendyent);//true
        System.out.println(stendyent instanceof Person);//true
        System.out.println(stendyent instanceof Object);//true
        //System.out.println(stendyent instanceof Teacher);//编译器报错
        //System.out.println(stendyent instanceof String);//编译器报错
         */
    }
}


这篇关于instanceof的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程