多态指的是同一个类实例的相同方法在不同情形下有着不同的表现形式,在Java中多态分为两个,一个是向上转型,一个是向下转型
1.向上转型(编程中遇到的绝大多数情况)
一般用于参数统一化
父类 父类引用 = new 子类();
2.向下转型(编程中遇到的少部分情况)
一般用于父类引用需要调用子类扩充方法时。
子类 子类引用 = (子类)父类实例;
注:1.向下转型需要强转
2.向下转型必须先发生向上转型,否则会报ClassCastExceotion:发生在2个不能强转的类之间。
eg.
class Person{
public void print(){
System.out.println("1.我是爸爸");
}
}
class Student extends Person{
public void print(){
System.out.println("2.我是儿子");
}
}
public class Ex1 {
public static void main(String[] args) {
//正常,子类引用等于子类实例
Student stu = new Student();
stu.print();
//向上转型,自动(虽然一个是Person类型,一个是Student类型,但是不用强转)
//不要看前面是谁的引用,只用看是谁new出来的,谁new用谁
Person per = new Student();
per.print();
//向下转型(要发生向下转型,必须先发生向上转型)
Student stu = (Student)per;//亲子鉴定,告诉父亲这是儿子
stu.print();
//现在就new了一次,说白了stu这个对象也是通过上面的new Student()出来的
//看这种东西不要看前面,只用看new在哪,调用的方法有没有被new这个类覆写,则调用的一定是被覆写后的方法
}
}
3. instanceof 关键字
instanceof 是 Java 的一个二元操作符,类似于 ==,>,< 等操作符。
instanceof 是 Java 的保留关键字。它的作用是测试它左边的对象是否是它右边的类的实例,返回 boolean 的数据类型。
所以可以在向下转型前引用 instanceof 类来判断一下(如果不能就先向上转型一下)
eg.
class Person3{
public void print(){
System.out.println("1.我是爸爸");
}
}
class Student3 extends Person3{
public void print(){
System.out.println("2.我是儿子");
}
}
public class Ex3 {
public static void main(String[] args) {
Person3 per3 = new Person3();
System.out.println(per3 instanceof Person3);
System.out.println(per3 instanceof Student3);
if (! (per3 instanceof Student3)){
//向上转型后输出为true
per3 = new Student3();
}
System.out.println(per3 instanceof Student3);
}
}
4.参数统一化
例:Person这个类是一个父类,他下面有Worker,Student这些子类,要求设计一个方法,该方法可以接收Person及其子类对象,并调用Person类的print()方法。
如果用重载,需要重载四次,使用向上转型可以大量节约代码。
/*
参数统一化,不管有多少子类一个方法就可以搞定,
*/
class Person2{
public void print2(){
System.out.println("Person类的print方法");
}
}
class Student2 extends Person2{
public void print2(){
System.out.println("Student类的print方法");
}
}
class Worker2 extends Person2{
public void print2(){
System.out.println("Worker类的print方法");
}
}
public class Ex2 {
public static void main(String[] args) {
//要求:定义一个方法,接受Person类的所有子类对象并调用print()
fun(new Person2());//自己等于自己
fun(new Student2());//向上转型(Preson2 per2 = new Student2)
fun(new Worker2());//向上转型
}
public static void fun(Person2 per2){
per2.print2();
}
// public static void fun(Student2 stu2){
// stu2.print();
// }
// public static void fun(Worker2 Wor2){
// Wor2.print();
// }
// 这样一个一个重载过于麻烦,Student,Worker或者其他的子类都可以向上转型变成Person
}