Java 多态

来源:互联网 发布:java位运算 编辑:程序博客网 时间:2024/05/21 08:43

多态:父类或接口引用子类实例的现象

1、多态非静态方法访问中,父类访问的是子类的方法,父类不能调用子类的特有方法。若多态访问的是静态方法,则调用的是引用的静态方法。

class Animal{void eat(){System.out.println("eat food");}}class Dog extends Animal{void eat(){System.out.println("eat bone");}void run(){System.out.println("run fast");}}public class Demo{public static void main(String[] args){Animal dog = new Dog();dog.eat();//调用子类的eat方法//dog.run();  报错,父类不能调用子类的特有方法。Dog dog1 = (Dog)dog;dog1.run();//向下转换类型,调用成功。}}

2、多态是对方法而言,对成员变量不存在多态

class Animal{int age = 10}class Dog extends Animal{int age = 15;}public class Demo{public static void main(String[] args){Animal dog = new Dog();System.out.println(dog.age);//打印的是10,即父类的成员变量}}

0 0
原创粉丝点击