Java三大特性之一之多态
多态,指某一样事物的多样性。
在java中,多态的前提是:
1 有继承或者实现关系
2 有方法的重写
多态的好处:提高程序扩展性,对于某一类有共同特性的对象,我们可以抽象出他们的父类,通过操作父类来指挥一堆对象做事情。
多态的体现:把一个子类对象当做一个父类对象来看,或者说父类引用指向之类对象。即Person p = new Student();这种形式。
多态的缺陷:访问的局限性,比如上例中p只能访问Person类中的方法,不能访问Student类中的方法。
多态最基本两个定理:
定理一 当我们把一个子类对象当做父类对象来看时,比如Person p = new Student();只能访问父类中的方法,不能访问子类中的方法:
例如,定义父子类Person Student如下:
- package com.anjoyo.demo;
- public class Person {
- private String name;
- private int age;
- public Person() {
- }
- public Person(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public void move(){
- System.out.println("Person move !");
- }
- }
定义Student类,Student继承自Person
- package com.anjoyo.demo;
- public class Student extends Person{
- public void study(){
- System.out.println("learn");
- }
- }
测试类代码如下:
- package com.anjoyo.demo;
- public class TestStudent {
- public static void main(String[] args) {
- Person p =new Student();
- p.move();
- //p.study();
- //报语法错误:The method study() is undefined for the type Person
- }
- }
可以看出p对象不能调用子类Student的方法study()。
定理二 当我们把一个子类对象当做父类对象来看时,比如Person p = new Student();如果在子类中重写(覆盖)了父类中的方法,在调用该方法时,调用的是子类的方法。
比如在Student类中重写move方法,如下:
- package com.anjoyo.demo;
- public class Student extends Person{
- public void study(){
- System.out.println("learn");
- }
- public void move(){
- System.out.println("Student running !");
- }
- }
在测试类中用p再调用move()方法时,输出的是Student running !
- package com.anjoyo.demo;
- public class TestStudent {
- public static void main(String[] args) {
- Person p =new Student();
- p.move();//Student running !
- }
- }
转载于:https://blog.51cto.com/632977922/1075004