Java中的静态分派和动态分派

静态分派

有如下代码:

public abstract class Human {}
public class Man extends Human {}
public class Woman extends Human {}

在客户端定义了几个方法并调用如下:

public class Client {

    public static void main(String[] args){
        Human man = new Man();
        Human woman = new Woman();
        Client client = new Client();
        client.sayHello(man);
        client.sayHello(woman);
    }

    public void sayHello(Human human){
        System.out.println("hello, human");
    }

    public void sayHello(Man man){
        System.out.println("hello, man");
    }

    public void sayHello(Woman woman){
        System.out.println("hello, woman");
    }

}

输入结果为:

hello, human
hello, human

静态分派:对应Java语言的重载(Overload)概念,根据参数静态类型选择对应方法。


动态分派

有如下代码:

public abstract class Human {
    abstract void sayHello();
}

public class Man extends Human {

    @Override
    void sayHello() {
        System.out.println("man say hello");
    }
}

public class Woman extends Human {

    @Override
    void sayHello() {
        System.out.println("woman say hello");
    }
}

在客户端调用:

public class Client {

    public static void main(String[] args){
        Human man = new Man();
        Human woman = new Woman();
        man.sayHello();
        woman.sayHello();
    }
}

输入结果为:

man say hello
woman say hello

动态分派:对应Java语言的重写(Override)概念,根据参数实际类型选择对应方法

你可能感兴趣的:(Java中的静态分派和动态分派)