我们知道按照现有类的类型来创建新类的方式为继承。
换句话说 “新类是现有类的一种类型”
因为继承可以确保父类中所有的方法在子类中也同样有效,所以能够向父类发送的所有信息也同样可以向子类发送。
这儿有一个例子:
public class Test {
public static void main (String [] args) {
Test test = new Test();
Animal a = new Animal ("name");
Cat c = new Cat("catname","blue");
Dog d = new Dog("dogname","black");
test.f(a);
test.f(c);//将子类对象传递给了父类的引用 Animal a。
test.f(d);
}
public void f (Animal a) {//参数为Animal对象
System.out.println("name = " +a.name);
}
}
class Animal {
public String name;
Animal (String name){
this.name = name;
}
}
class Cat extends Animal {
public String eyeColor;
Cat (String name,String eyeColor) {
super(name);
this.eyeColor = eyeColor;
}
}
class Dog extends Animal {
public String furColor;
Dog (String name,String furColor) {
super(name);
this.furColor = furColor;
}
}
运行结果:
在其中我们可以发现
方法 public void f (Animal a) 中形参数 Animal对象
但test.f(c),与test.f(d); //将子类对象c、d 传递给了父类的引用 Animal a。我们将其称为向上转型
一、向上转型
概念:把对某个对象的引用看作其父类对象的引用的做法称为向上转型。即父类对象的引用指向子类对象。
向上转型中的一些规则:
-
父类对象的引用可以指向子类对象
-
一个父类的引用不可以访问其子类对象新增加的成员(属性和方法)。
(即把子类对象看做父类对象。。比如:将一个狗类对象dog1,传给其父类-动物类。则只能将dog1看做动物,不能看做狗。具体表现为:dog1能实现动物类中的方法(叫、跑)但不能实现狗类中的方法(游泳))
注:子类中重写的方法除外,这里涉及到多态的知识,后面会提到。 -
可以使用 引用对象 instanceof 类名:判断该引用型变量所指的 对象 是否属于 该类或该类的子类。
举个栗子:
public 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 );
System.out.println(c instanceof Animal );
System.out.println(d instanceof Animal );
System.out.println(c instanceof Cat );
System.out.println(d instanceof Dog );
a = new Dog("BigYellow","yellow");//向上转型 父类引用a指向了子类对象
System.out.println(a instanceof Animal );
System.out.println(a instanceof Dog );
System.out.println(a.name);
//System.out.println(a.furColor);//编译报错。
//因为一个父类的引用不可以访问其子类对象新增加的成员(属性和方法)
Dog d1 = (Dog) a;//强制转换,向下转型。子类引用指向父类对象
System.out.println(d1.furColor);
}
}
class Animal {
public String name;
Animal (String name){
this.name = name;
}
}
class Cat extends Animal {
public String eyeColor;
Cat (String name,String eyeColor) {
super(name);
this.eyeColor = eyeColor;
}
}
class Dog extends Animal {
public String furColor;
Dog (String name,String furColor) {
super(name);
this.furColor = furColor;
}
}
运行结果:
。
向下转型:
与向上转型相反
见上诉例子中:Dog d1 = (Dog) a;//强制转换,向下转型。子类引用指向父类对象
注意
不是所有的对象都可以向下转型,只有这个对象原本是子类对象通过向上转型得到的时候才能成功的向下转型。