多态

多态

多态存在的必要条件

  1. 必须要有继承关系

  2. 子类必须要重写父类的方法

  3. 父类的引用指向子类的对象

人类(父类)

/**
* 人类(父类)
*/
public class Person {
   public void eat(){
       System.out.println("人类的吃饭方法");
  }
}

学术类(子类)

 

/**
* 学生类(子类)
*/
public class Student extends Person {  //继承父类
   @Override
   public void eat() {
       System.out.println("学生的吃饭方法");   //重写了父类的方法
  }
}

测试类

/**
* 测试类
*/
public class Application {
   public static void main(String[] args) {
       Student student = new Student();
       Person person = new Student();  //父类的引用指向了子类的对象

       student.eat();  //因为自身就是student对象,所有输出的就是重写后的方法 “学生的吃饭方法”
       person.eat();   //因为student重写了person的方法,所有这里输出的是 “学生的吃饭方法”
  }
}

注意

  • 多态的是方法多态,并不是属性多态。

posted @ 2020-08-04 17:18  UnXun  阅读(78)  评论(0)    收藏  举报