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

    对象转型:

      1、一个基类的引用类型变量可以指向其子类对象

      2、一个基类的引用对象不可以访问其子类对象新增加的成员(属性和方法)

      3、可以使用引用变量instanceof

      4、子类的对象可以当做父类的对象称为向上转型,反之称为向下转型

    例如:

    package 对象转型;
    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 Dog extends Animal{
    	public String furColor;
    	Dog(String n,String c){
    		super(n);
    		furColor = c;
    	}
    }
    class test_01 {
    	public static void main(String[] args) {
    		Animal a = new Animal("name");
    		Cat c = new Cat("catname","blue");
    		Dog d = new Dog("dog","black");
    		System.out.println(a instanceof Animal);
    		System.out.println(c instanceof Animal);
    		System.out.println(d instanceof Animal);
    		System.out.println(a instanceof Cat);
    		
    		a = new Dog("bigyellow","yellow");
    		System.out.println(a.name);
    		System.out.println(a.furname);   //!error
    		System.out.println(a instanceof Animal);
    		System.out.println(a instanceof Dog);
    		Dog d1 = (Dog)a;  //要将强制转化符
    		System.out.println(d1.furColor);
    	}
    }
    

      标红的的代码内存情况是:

      

    a = new Dog("bigyellow","yellow");
    a是Animal类型的,只指向父类的,同理,只能访问父类的属性,也就是图中的name不能访问子类的属性Furcolor,如果访问的话,可以加个强制转化符,强制转换成Dag类型的
    Dog d1 = (Dog)a; 
  • 相关阅读:
    马士兵_聊天系统_知识储备库
    最近一些情况
    JAVA坦克大战项目练习日4
    JAVA坦克大战项目练习日3
    JAVA坦克大战项目练习日2
    JAVA坦克大战项目练习日1
    课后实战String的一些细节
    Java从入门到精通之数组篇
    58_自定义标签打包以及使用自定义标签教程
    javaWeb安全篇(1)——防盗链技术的实现
  • 原文地址:https://www.cnblogs.com/white-the-Alan/p/10178284.html
Copyright © 2011-2022 走看看