当前位置:网站首页>Jvm: when a method is overloaded, the specific method to call is determined by the static type of the incoming parameter rather than the actual type of the parameter

Jvm: when a method is overloaded, the specific method to call is determined by the static type of the incoming parameter rather than the actual type of the parameter

2022-06-23 05:42:00 amadeus_ liu2

One 、 Example

package com.example.controller;

public class TestOverload {
    public static void main(String[] args) {
        Grandpa grandpa=new Grandpa();
        Grandpa father=new Father();
        Grandpa offspring=new Offspring();

        print(grandpa);
        print(father);
        print(offspring);

    }

    public static void print(Grandpa grandpa){
        System.out.println("print grandpa......");
    }

    public static void print(Father father){
        System.out.println("print father......");
    }

    public static void print(Offspring offspring){
        System.out.println("print offspring......");
    }
}

class Grandpa{

}
class Father extends Grandpa {

}
class Offspring extends Father{

}

Two 、 Operation output :
 Insert picture description here
3、 ... and 、 analysis :
grandpa、father、offspring this 3 Object's Static type All are Grandpa, Their Actual type Namely Grandpa、Father、Offspring,
Will this 3 Objects passed to print When the method is used , Because their static type is Grandpa, So they call

    public static void print(Grandpa grandpa){
        System.out.println("print grandpa......");
    }
原网站

版权声明
本文为[amadeus_ liu2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230350308547.html