龙空技术网

Java一道简单的面试题,考察方法调用,看看能不能答对?

Java猿 32

前言:

眼前各位老铁们对“java静态方法调用实例方法”大约比较关怀,看官们都需要知道一些“java静态方法调用实例方法”的相关文章。那么小编在网络上网罗了一些对于“java静态方法调用实例方法””的相关知识,希望姐妹们能喜欢,我们一起来了解一下吧!

method invoke

Java方法调用可以是解析调用,或者是分派调用,无论什么方式,目的就是找到适合的方法。

解析调用比较简单,在编译的时候就确定了调用的目标方法,这类方法在运行期间是不变的,比如静态方法。

分派调用又分为静态分派和动态分派,静态分派通过静态类型就能确认调用方法。先看下面的代码的输出。

public class TestMethodInvoke {    class Animal { }    class Cat extends Animal {    }    class Dog extends Animal {    }    private void run(Animal animal) {        System.out.println("Animal run!");    }    public void run(Cat cat) {        System.out.println("Cat run!");    }    public void run(Dog dog) {        System.out.println("Dog run!");    }    public static void main(String[] args) {        TestMethodInvoke test = new TestMethodInvoke();        Animal man = test.new Dog();        Animal woman = test.new Cat();        test.run(man);        test.run(woman);    }}

对有经验的开发者,很容易知道上面程序的执行结果。

Animal run!Animal run!

如果你的答案不是这个也没有关系,我来简单说明下静态类型和运行时类型,变量Animal成为静态类型,Cat或者Dog则被称为运行时类型。编译器是根据参数的静态类型来选择调用方法的版本,叫做静态分派。

        TestMethodInvoke test = new TestMethodInvoke();//        Animal man = test.new Dog();//        Animal woman = test.new Cat();        test.run(test.new Dog());        test.run(test.new Cat());

以上代码简单改了参数的类型,执行结果又是另外一种情形,结果如下,

Dog run!Cat run!

以下是一个测试题,大家可以执行试试,结果后续在发布到评论区。

public class TestOverLoad {    public static void hi(Object obj) {        System.out.println("Hi Object");    }    public static void hi(Long obj) {        System.out.println("Hi Long");    }    public static void hi(Comparable comparable) {        System.out.println("Hi Comparable");    }    public static void main(String[] args) {        hi(1000_0000);    }}

标签: #java静态方法调用实例方法