令人困惑的“覆盖私人方法” [英] Confusing "override a private method"

查看:119
本文介绍了令人困惑的“覆盖私人方法”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此代码有两个问题

public class Override {
    private void f() {
        System.out.println("private f()");
    }
    public static void main(String[] args) {
        Override po = new Derived();
        po.f();
    }
}

class Derived extends Override {
    public void f() {
        System.out.println("public f()");
    }
} 

/*
* Output: private f()
*/// :~

1)如何在Override po的引用上看到函数f;

1) How is function f is visible on the reference of Override po;

2)为什么输出private f()

2) Why is output "private f()"

推荐答案


  1. main 方法在类覆盖中,所以当然它可以看到类的私有成员覆盖

  1. The main method is inside class Override, so ofcourse it can see the private members of class Override.

重写方法 f in class 派生,没有多态。变量 po 的类型是覆盖,因此它将采用方法 f 来自班级覆盖

You are not overriding method f in class Derived, there is no polymorphism. The type of the variable po is Override, so it will take method f from class Override.

请注意类中的方法 f 在类 Derived C>。类派生中的方法 f 是一种不同的方法,与方法<$没有任何关系c $ c> f 在超类中。

Note that method f in class Override is not visible at all in class Derived. The method f in class Derived is a different method, that doesn't have anything to do with the method f in the superclass.

这篇关于令人困惑的“覆盖私人方法”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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