关于多态:
来看一个案例:
1.向上转型
package com.kxy.poly;
class Animal{
String name="动物";
public void sleep() {
System.out.println("睡");
}
public void run() {
System.out.println("跑");
}
public void eat() {
System.out.println("吃");
}
}
class Cat extends Animal{
public void eat() {
System.out.println("猫吃鱼");
}
public void catchMouse() {
System.out.println("猫抓老鼠");
}
}
class Dog extends Animal{
public void eat() {
System.out.println("狗吃骨头");
}
public void cry() {
System.out.println("汪汪汪!~");
}
}
public class poly01 {
public static void main(String[] args) {
Animal animal=new Cat();//向上转型
animal.eat();
// animal.catchMouse();//向上转型实例化的对象不能访问子类特有成员
animal =new Dog();//animal的地址更改为指向dog类
animal.eat();
// animal.cry();//同样不能访问狗的特有成员
}
}
这就是向上转型,精通向上转型你只需要掌握下面几个知识点:
1.本质:父类的引用指向了子类的对象
2.语法:父类 引用名 =new 子类();
3.特点(非常重要)编译类型看左边,运行类型看右边。
可以调用父类中原有的所有成员(需遵守访问权限)但不能调用子类中特有成员。
2.向下转型
package com.kxy.poly;
class Animal{
String name="动物";
public void sleep() {
System.out.println("睡");
}
public void run() {
System.out.println("跑");
}
public void eat() {
System.out.println("吃");
}
}
class Cat extends Animal{
public void eat() {
System.out.println("猫吃鱼");
}
public void catchMouse() {
System.out.println("猫抓老鼠");
}
}
class Dog extends Animal{
public void eat() {
System.out.println("狗吃骨头");
}
public void cry() {
System.out.println("汪汪汪!~");
}
}
public class poly01 {
public static void main(String[] args) {
Animal animal=new Cat();//向上转型
animal.eat();
// animal.catchMouse();//向上转型实例化的对象不能访问子类特有成员
Cat cat=(Cat) animal;
cat.eat();
cat.catchMouse();//向下转型可以访问特有属性和方法
//Dog dog= (Dog) animal;//此时animal不再是父类,不能用子类Dog强制转换子类Cat
//dog.cry();
}
}
1.语法:子类 引用名 =(子类)父类引用;
2.只能强制转换父类的引用,不能是父类
3.要求父类的引用必须指向的是当前目标类型的对象,就本案例来讲,就是animal必须指向Cat类
4.可以调用子类中所有成员。