即同一方法可以根据发送对象的不同而采用多种不同的行为方式
一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多
多态存在的条件
注意
1.多态是方法的多态,属性没有多态
2.父类和子类,有联系 类型转换异常! ClassCastException!
3.存在的条件:继承关系,方法需要重写,父类引用指向子类对象! Father father= new Son();
示例
public class Application {
public static void main(String[] args) {
//一个对象的实际类型是确定的
//new Student();
//new Person();
//但是,指向引用类型就不确定了:父类的引用指向子类
//Student 能调用的方法都是自己的或者继承父类的!
Student s1 = new Student();
//Person 父类,可以指向子类,但不能调用子类独有的方法,如果父类要用子类的方法需要向下转型
Person s2 = new Student();
Object s3 = new Student();
//对象能执行哪些方法,主要看对象左边的方法,和右边关系不大!
s2.run();//子类重写了父类的方法,执行子类的方法
s1.eat();
}
}
父类
public class Person {
public void run() {
System.out.println("run");
}
}
子类
public class Student extends Person {
@Override
public void run() {
System.out.println("son");
}
public void eat() {
System.out.println("eat");
}
}
输出
son
eat
子类转换为父类,向上转型(不用强制转换)
父类转换为子类,向下转型(要强制转换)
父类的引用指向子类的对象
方便方法的调用
代码示例:
public class Application {
public static void main(String[] args) {
//类型之间的转换:父 -> 子
//高 低
Person student = new Student();
//student 将这个对象转换成Student类型,我们就可以用Student类型的方法了!
//父类转子类
((Student) student).go();
//子类转换父类,可能丢失自己的本来的一些方法
Student student1 = new Student();
student1.go();
Person person = student1;
//person.go(); 无效,子类转父类,方法丢失
}
}
父类
public class Person {
}
子类
public class Student extends Person {
public void go() {
System.out.println("go");
}
}
输出
go
go
原文:https://www.cnblogs.com/dt746294093/p/14638959.html