多态性:一个事物的多种形态
使用前提: ① 类的继承关系 ② 方法的重写
Person p1 = new Man();
父类的引用 指向 子类的对象(或 子类的对象 赋给 父类的引用 )
只适用于方法,不适用于属性(编译和运行都看左边)!
class Base {
int count = 7;
public void display() {
System.out.println(this.count);
}
}
class Sub extends Base {
int count = 17;
public void display() {
System.out.println(this.count);
}
}
public class FieldMethodTest {
public static void main(String[] args) {
Sub s = new Sub();
System.out.println(s.count);//17
s.display();//17
Base b = s; //多态性 赋值就是地址
//== :比较的是两个引用数据类型变量的地址值是否相同
System.out.println(b == s);//true
System.out.println(b.count);//7,属性值没有改变
b.display(); //17,但方法改变了
}
}

虚拟方法调用
编译,看左边;运行,看右边。在编译期,只能调用父类中声明的方法,但在运行期,我们实际执行的是子类重写父类的方法。
Instanceof 亲子鉴定
点击查看`Instanceof`操作符
public class PersonInstanceof {
public static void main(String[] args) {
PersonInstanceof test = new PersonInstanceof();
test.method( new Person() );
System.out.println("************");
test.method( new Student() );
System.out.println("************");
test.method( new Graduate() );
}
public void method( Person e ){
//虚拟方法调用
String info = e.getInfo();
System.out.println(info);
//测试方法一
if(e instanceof Graduate){
System.out.println("a graduated student");
System.out.println("a student");
System.out.println("a person");
}else if(e instanceof Student){
System.out.println("a student");
System.out.println("a person");
}else{
System.out.println("a person");
}
//测试方法二
/*
if(e instanceof Graduate){
System.out.println("a graduated student1");
}
if(e instanceof Student){
System.out.println("a student1");
}
if(e instanceof Person){
System.out.println("a person1");
}
*/
}
}
class Person {
protected String name = "Liuzhen";
protected int age = 23;
public String getInfo() {
return "PersonName: " + name + "\n" + "Personage: " + age;
}
}
class Student extends Person {
protected String school = "SHU";
public String getInfo() {
return "StudentName: " + name + " age: " + age + " school: " + school;
}
}
class Graduate extends Student {
public String major = "Math";
public String getInfo() {
return "Name: " + name + "\nage: " + age + "\nschool: " + school + "\nmajor:" + major;
}
}
RunResult:

浙公网安备 33010602011771号