对象转型(casting)
一个基类的引用类型变量可以指向其子类的对象
一个基类的引用不可以访问其子类对象新增加的方法(属性,方法)
可以使用 引用 变量instanceof类名 来判断该引用型变量所指向的对象是否属于该类或该类的子类
子类的对象可以当作基类的对象来使用称作向上转型(upcasting),反之则称为向下转型(downcasting)
这里来看第一段程序:
class Animal{
public String name;
Animal(String name){
this.name = name;
}
}
class Dog extends Animal{
public String furColor;
Dog(String n,String c){
super(n);
furColor = c;
}
}
public class TestCasting {
public static void main(String[] args) {
Animal a = new Animal("name");
Dog d = new Dog("dogname" , "yellow");
System.out.println(a instanceof Animal);
System.out.println(d instanceof Animal);
System.out.println(a instanceof Dog);
a = new Dog("bigyellow" , "yellow");
System.out.println(a.name);
//System.out.println(a.furname);
System.out.println(a instanceof Animal);
System.out.println(a instanceof Dog);
Dog d1 = (Dog)a;
System.out.println(d1.furColor);
}
}
简单来分析一下,其中有两个类,一个是父类Animal类以及继承的子类Dog类,Animal中有一个name的构造方法
Dog中,有furColor的成员变量。再看main类,分别是new了一个Animal类 a,和new了一个Dog类d,并且还附上了属性。
之后通过instanceof来判定,a是否属于Animal类,然后初步调试一下
这时我们把a来new成了一只Dog类,同时还给他增加了属性,进行一下内存分析
这里在计算机的视角里只能看到a有animal的属性和方法,也就是说它作为Dog的furcolor是无法看到的,总结一下:只能看到父类的,而子类的无法看到
但实际上,a既是一只Dog又是一只Animal
再来进一步的调试程序:
分别输出a的name,a是否为Animal和Dog
此时如果我们想得到a的furname属性呢?
System.out.println(a.furname);
这句话是不对的,目前a无法访问furcolor,但是我就想访问a的furColor变量,这里我们采用强制转换,让d1转换成a并指向Dog的属性
Dog d1 = (Dog)a;
这条语句执行完后,那么d1便有了作为Dog的属性
这时可以通过d1.furColor来访问它的属性
这就是对象转型