一.多态性
Java引用变量有两种类型:一个是编译时类型,一个是运行时类型。编译时类型由声明该变量的类型所决定,运行时类型由实际赋给该变量的对象类型决定。
所谓多态就是类型相同在调用同一个方法时呈现出不同输出结果。多态出现的条件:
1.存在继承关系
2.存在子类重写父类方法的情况 举例:
Person.java
public class Person {
int eyesNum=2;
int hairColor;
public void eat(){
System.out.println("I want to eat food");
}
}
student.java
public class student extends Person{
String stuNum;
String nianji;
public void eat(){
System.out.println("I am student, I want to eat food");
}
public static void main(String[] args){
Person student=new student();//父类引用指向子类对象
Person p=new Person();
student.eat();
p.eat();
}
}
运行结果:
在上边程序中student类继承了Person类,并且student类重写了Person类的eat()方法,在main方法中引用变量student和p均是Person类型,但是在调用同一个方法eat()时出现了不同的输出结果。
分析多态出现的原因:前边已经提到了一个引用变量存在编译时类型和运行时类型,在上边程序中student对象和p对象在编译时类型都是Person类型,然而在运行时student对象的类型变成了student,所以student对象会调用子类中的重写的eat()方法
注:成员变量不具备多态性,通过引用变量来访问其包含的实例变量,系统总是试图访问它编译时类型所定义的成员变量,而不是运行时类型所定义的成员变量
二.引用变量类型的转换
在上边提到过,Java程序存在两种类型一种是编译时类型一种是运行时类型,所以当存在父类引用只想子类对象时,如果该对象直接调用某一个子类含有而父类不含有的方法时,在编译时是不能通过的(注:这里要和多态不要混淆,多态的出现条件之一是子类必须重写父类的某一方法,并且在调用时调用这类方法),所以这里就牵扯到引用变量类型的转化问题:
所以当父类引用指向子类对象的情况出现时要想调用运行时子类类型的对象的特有方法时需要对引用类型进行强制转化。eg:
student.java
public class student extends Person{
String stuNum;
String nianji;
public void eat(){
System.out.println("I am student, I want to eat food");
}
public void changeNianji(String nianji){
this.nianji=nianji;
}
public static void main(String[] args){
Person student1=new student();//父类引用指向子类对象
Person p=new Person();
student1.eat();
p.eat();
((student) student1).changeNianji("");
}
}
在上边程序中出现了父类引用Person指向了子类对象student1,在student中存在父类不存在的方法changeNianji(),所以要想通过student1对象来调用changeNianji()方法就需要进行类型的转化。