直接在子类的对象上调用时的静态和私有方法行为听起来像是覆盖? [英] static and private method behavior when calling direct on object of child class sounds like overriding?

查看:98
本文介绍了直接在子类的对象上调用时的静态和私有方法行为听起来像是覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class B extends A{

    public static void main(String[] args) {
    new B().privateMethod();//no error -output B-privateMethod.Sounds like overriding
    new B().staticMethod(); //no error -output B-StaticMethod.Sounds like overriding
    }

    private void privateMethod() {
        System.out.println("B-privateMethod.");
    }
    static void staticMethod() {
        System.out.println("B-StaticMethod.");
    }
}


class A{
    private void privateMethod() {
        System.out.println("A-privateMethod.");
    }
    static void staticMethod() {
        System.out.println("A-StaticMethod.");
    }
}

在R& DI上发现privateMethod() -由于此方法在子类的对象上不可用,因此子类和父类的privateMethod()是单独的方法,并且它们之间没有关系,因此不会被覆盖。
,但是如果使用staticMethod()-父类的方法在子类的对象上可用,当我们在子类中定义此方法时,子类的对象开始指向子类的方法。覆盖但不覆盖,因为静态方法不会覆盖。

On R&D I found in case of privateMethod()- since this method was not available on object of child class so child class's and parent class's privateMethod() are separate method and they have no relationship so this is not overriding. but in case of staticMethod()- parent class's method was available on object of child class ,and when we define this in child class, object of child class start pointing to child class method.this looks like method overriding but not,since static method does not override.

java开发工具包如何处理静态方法?

how does static method handle by java developement kit?

推荐答案

多态性不适用于静态方法。静态方法通过JVM指令invokestatic进行调用,而多态性通过invokevirtual实现。静态方法的调用在编译时确定,而多态方法在运行时动态调度。

Polymorphism is not for static methods. Static methods are called with JVM instructions invokestatic, whereas polymorphism is achieved with invokevirtual. The calls to static methods are determined at compile time, and polymorphic methods are dynamically dispatched at runtime.

只需将新B()分配给类型A的变量,就可以轻松地调整代码,以便调用A.staticMethod()。

You can easily tweak your code so that A.staticMethod() is called, by just assigning new B() to a variable of type A.

public static void main(String[] args) {
    new B().privateMethod();
    A b = new B(); // change here.
    b.staticMethod(); // A.staticMethod() is called here. 
}

这篇关于直接在子类的对象上调用时的静态和私有方法行为听起来像是覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆