jvm静态分派和动态分派
作者:互联网
package com.jvm.dispatch;
/**
* @author JTY
* @date 21-2-20 23:44
* @description
* 静态分派 编译期间根据静态类型(外观类型)确定目标方法,典型的有方法重载
* 方法动态分派 运行期间根据运行时类型(实际类型)确定目标方法,典型的有方法重写
*/
public class DynamicDispatch {
static abstract class Human {
abstract protected void sayHello();
}
static class Woman extends Human {
@Override
protected void sayHello() {
System.out.println("hello woman!");
}
}
static class Man extends Human {
@Override
protected void sayHello() {
System.out.println("hello man!");
}
}
/*** 验证字段没有多态性,子类字段覆盖父类字段 */
static class Father extends Human {
public int age = 40;
public Father() {
age = 50;
showAge();
}
public void showAge() {
System.out.println("I'm father,my age is " + age);
}
@Override
protected void sayHello() {
System.out.println("hello Father!");
}
}
static class Son extends Father {
public int age = 20;
public Son() {
age = 10;
showAge();
}
public void showAge() {
System.out.println("I'm Son,my age is " + age);
}
@Override
protected void sayHello() {
System.out.println("hello Son!");
}
}
/*** 验证方法重载的静态分派 */
static void printClassType(Human m) {
System.out.println("this type is Human");
}
static void printClassType(Woman m) {
System.out.println("this type is Woman!");
}
static void printClassType(Man m) {
System.out.println("this type is Man!");
}
public static void main(String[] args) {
Human m = new Man();
//编译期间根据静态类型确定调用方法为 printClassType(Human m)
printClassType(m);
//运行期间根据实际类型确定调用方法为 Man::sayHello()
m.sayHello();
m = new Woman();
//编译期间根据静态类型确定调用方法为 printClassType(Human m)
printClassType(m);
//运行期间根据实际类型确定调用方法为 Woman::sayHello()
m.sayHello();
//验证字段没有动态分派,当使用子类方法访问父类、子类同字段时,只会访问到子类的字段
Son son = new Son();
Father fa = son;
/*
* I'm Son,my age is 0 实际类型是Son,由于动态分派,父类Father构造方法中调用的showAge()为Son::showAge(),
* 访问到的属性为Son.age,由于父类的构造方法在子类初始化之前,此时访问到的为jvm默认的初始值0
* I'm Son,my age is 10 子类的方法调用时age字段已经被赋值为10
* hello Son! 方法具有多态性,调用实际类型的方法
* son age is 10 Son类型的字段值
* father age is 50 Father类型的字段值
* */
son.sayHello();
/*** 此时使用静太类型访问到的父类中的字段值 */
System.out.println("son age is " + son.age);
/*** 此时使用静太类型访问到的子类中的字段值 */
System.out.println("father age is " + fa.age);
}
}
标签:静态,age,System,分派,Son,jvm,println,void,out 来源: https://www.cnblogs.com/jinit/p/14424027.html