多态存在的条件
- 类之间有继承关系
- 子类需要重写父类的方法
- 父类的引用类型指向子类对象
Person类(父类)
package com.oop.demo05;
public class Person {
public void say(){
System.out.println("hello,Person");
}
public void hi(){
System.out.println("hei");
}
}
Student类(子类)
package com.oop.demo05;
public class Student extends Person{
public void say(){
System.out.println("hello,Student");
}
public void hello(){
System.out.println("hi");
}
}
主类
package com.oop.demo05;
public class Application {
public static void main(String[] args) {
/*
1.一个类的实际对象是确定的 new Person new Student
2.可以指向的应用类型就不确定了:父类的引用指向子类
*/
// Student类能调用的方法都是自己的或者是继承父类的
Student s1 = new Student();
// Person类 可以指向子类(Student) 但是不能调用子类独有的方法
Person s2 = new Student();
s1.say(); // 子类重写了父类的方法
s2.say();
// 对象能执行那些方法,主要看左边的类型,和右边关系不大
s1.hello();
//s2.hello(); //报错 因为该方法不是重写 方法只在子类中存在
// 父类有 子类没有 直接调用父类
s1.hi();
s2.hi();
}
}
运行结果