多态
1. 即同一方法可以根据发送对象的不同而采取多种不同的行为方式
2. 一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多
多态存在的条件
有继承关系
子类重写父类方法
父类引用指向子类对象
注意:
多态是方法的多态,属性没有多态父类和子类,有联系 类型转换异常 ClassCastException存在条件: 继承关系 方法需要重写, 父类引用指向子类对象
static 方法 属于类不属于实例final 常量private 方法
package com
.etc
.ood
.demo3
;
public class Person {
public void run(){
System
.out
.println("person");
}
}
package com
.etc
.ood
.demo3
;
public class Student extends Person{
@Override
public void run() {
System
.out
.println("student");
}
}
package com
.etc
.ood
;
import com
.etc
.ood
.demo3
.Person
;
import com
.etc
.ood
.demo3
.Student
;
public class Application {
public static void main(String
[] args
) {
Student s1
= new Student();
Person s2
= new Student();
Object s3
= new Student();
s1
.run();
s2
.run();
}
}