zoukankan      html  css  js  c++  java
  • java 25.向上/下转型,instanceof关键字

    对象的向上转型

    new一个Cat对象当作Animal对象来用,这时候animal只能使用Animal对象的方法,不能用Cat对象的方法。

    Animal animal = new Cat();
    

    对象的向下转型

    通过类似基本类型的强制转换来把CAT对象animal转换回原本的Cat对象cat,然后cat就可以使用Cat对象的方法。

    Cat cat = (Cat) animal;
    

    instanceof关键字

    在向下转型,也就是把对象从大范围还原回小范围的时候,为了保证还原的不出错(java.lang.classCastException),我们使用instanceof关键字来判断,要还原的对象是不是目标对象的实例,如果是,那我们就转。

    比如判断animal是不是Dog的实例类型animal instanceof Dog

    示例代码

    public class test {
        public static void main(String[] args) throws IOException {
            Animal animal = new Cat();
            animal.eat();
            
            if (animal instanceof Dog){
                Dog dog = (Dog) animal;
                dog.watchHouse();
            }
            
            if (animal instanceof Cat){
                Cat cat = (Cat) animal;
                animal.eat();
            }
        }
    }
    
    更多学习笔记移步 https://www.cnblogs.com/kknote
  • 相关阅读:
    第二次结对编程作业
    第5组 团队展示
    第一次结对编程作业
    第一次个人编程作业
    51 Nod 1024 Set
    51 Nod 1007 dp
    YY的GCD 数学
    选课 树形背包dp
    运输问题 费用流
    分配问题 费用流
  • 原文地址:https://www.cnblogs.com/kknote/p/15352395.html
Copyright © 2011-2022 走看看