java学习笔记;上转型对象以及继承与多态

猫和狗都属于动物类,但叫声不同,这就是叫声的多态。
而上转型对象则是用父类去定义对象,而用子类的构造方法创建它

假设Animal类是Tiger类的对象
Animal a;
a= new Tiger();
上转型对象可以操作子类继承或隐藏的成员变量,也可以调用子类继承和重写的方法(被重写导致隐藏的方法不能调用)。
其作用可以体现在下面的程序中;
package super1;
class 动物{
void cry() {
}
}
class 狗 extends 动物{
void cry() {
System.out.println(“汪汪大雪饼”);
}
}
class 猫 extends 动物{
void cry() {
System.out.println(“喵喵红烧鱼”);
}
}
public class Example5_11 {

public static void main(String[] args) {
	// TODO Auto-generated method stub
       动物 animal;
animal=new 狗();
animal.cry();
animal=new 猫();
animal.cry();
}

}
在这里插入图片描述

当有许多不同种类动物时也不需要多次建立不同对象。但上转型对象不能操作子类新增的成员变量(失去了这部分属性,例如动物类中只有叫,那么猫、狗上转后也只能“叫”,).。

猜你喜欢

转载自blog.csdn.net/Eysunvoes/article/details/88140414
今日推荐