当前位置:网站首页>2021-05-11instanceof和类型转换

2021-05-11instanceof和类型转换

2022-06-23 09:54:00 鹿其其鹿

public class Application {
    
    public static void main(String[]args){
    

        Object object = new Student();

        System.out.println(object instanceof Student);
        System.out.println(object instanceof Person);
        System.out.println(object instanceof Object);
        System.out.println(object instanceof Teacher);
        System.out.println(object instanceof String);

        //类型之间的转换:父 子
        //高 低
        Person obj = new Student();
        //student将这个对象转换为Student类型,我们就可以使用Student类型的方法了

        Student student = (Student) obj;
        student.go();

        //==((Student)obj).go();

        //子类转换为父类,可能丢失自己本来的一些方法
        Student student1 = new Student();
        student.go();
        Person person = student1;
        
        
    }
}

  1. 父类引用指向父类的对象
  2. 把子类转换为父类,向上转型
  3. 把父类转换为子类,向下转型:强制转换
  4. 方便方法的调用,减少重复的代码,简洁
  5. 抽象:封装 继承 多态
原网站

版权声明
本文为[鹿其其鹿]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_45478564/article/details/116664865