对象转型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; 
原文地址:https://www.cnblogs.com/white-the-Alan/p/10178284.html