zoukankan      html  css  js  c++  java
  • Java 对象转型

    对象转型

    • 规则一:一个基类的引用类型可以指向其子类对象。
    • 规则二:一个基类的引用不可以访问其子类对象新增加的成员(属性和方法)。
    • 规则三:可以使用“变量instanceof类名”来判断该引用是否指向该类或该类的子类。
    • 规则四:子类的对象可以当作基类的对象来使用称作向上转型,反之称作向下转型。
    class Animal
    {
        public String name;
        Animal(String name)
        {
            this.name = name;
        }
    }
    class Cat extends Animal
    {
        public String eyescolor;
        Cat(String n,String c)
        {
            super(n);
            eyescolor = c;
        }
    }
    class Dod extends Animal
    {
        public String furcolor;
        Dog(String n,String c)
        {
            super(n);
            furcolor = c;
        }
    }
    puclic class Test
    {
        public static void main(String args[])
        {
            Animal a = new Animal("name");
            Cat c = new Cat("catname","blue");
            Dog d = new Dog("dogname","black");
            
            System.out.println(a instanceof Animal);//true,规则三
            System.out.println(c instanceof Animal);//true,规则三
            System.out.println(d instanceof Animal);//true,规则三
            System.out.println(a instanceof Cat);//false,违反规则三
            
            a = new Dog("bigyellow","yellow");//规则一
            System.out.println(a.name);//bigyellow,规则二
            System.out.println(a.furname);//error,违反规则二
            System.out.println(a instanceof Animal);//true,规则三
            System.out.println(a instance Dog);//true,规则三
            //注意instanceof实际上看的是这个引用指向的对象,而不是这个引用的类型
            Dog d1 = (Dog)a;//强制转换,向下转型
            System.out.println(di.furcolor);//yellow
        }
    }
    
  • 相关阅读:
    ab Apache HTTP server benchmarking tool
    压缩JS的类
    看电影学人生:《白银帝国》有感
    JavaScript 闭包
    微软为asp.net ajax和jquery创建了CDN
    JavaScript工具
    Mysql初始化root密码和允许远程访问
    一步一步学Ruby(二十一):文件操作2
    测试包含HttpContext.Current的代码
    What’s the difference between <system.web> and <system.webServer>?
  • 原文地址:https://www.cnblogs.com/031602523liu/p/8654185.html
Copyright © 2011-2022 走看看