Java:为什么基类方法可以调用不存在的方法? [英] Java: Why could base class method call a non-exist method?

查看:94
本文介绍了Java:为什么基类方法可以调用不存在的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class BaseClass {
    private void f() {
        System.out.println("Baseclass f()");
    }

    public static void main(String[] args) {
        BaseClass dc = new DerivedClass();
        dc.f();
    }
}

class DerivedClass extends BaseClass {
    public void f() {
        System.out.println("DerivedClass f()");
    }
}

我认为,dc所引用的对象应仅具有一个 non-override 方法-public void f()方法,当使用BaseClass引用进行引用时,该方法将使其(public方法)不可见由于dc所引用的对象没有私有void f()方法,或者因为DeriverClass无法继承私有方法,所以dc所引用的调用方法f()又如何呢?

In my opinion, the object dc refers to should have only one non-override method - public void f() method,which make it(the public method) invisible when refered to with BaseClass reference.Since the object dc referes to does not have the private void f() method either because the DeriverClass could not inherit the private method,how could the object dc refers to call method f()?

谢谢.

推荐答案

四点:

(1)为了详细说明vivyzer编写的内容,代码得以编译,因为BaseClass中的main方法可以访问该类自己的私有方法.如果您将代码编写为:

(1) To elaborate on what vivyzer wrote, the code compiles because the main method in BaseClass has access to the class's own private methods. If you wrote the code as:

class BaseClass {
  private void f() { }
}

class DerivedClass {
  public void f() { }
}

class Bystander {
  public static void main() {
    BaseClass inst = new DerivedClass();
    inst.f();
  }
}

然后,该代码将无法编译.

Then the code would not compile.

(2)该语言允许它支持用例,在该用例中,基类的作者可以添加新的私有方法,而不必担心其他作者的派生类型.

(2) This is allowed by the language to support the usecase where the author of a base class can add a new private method without worrying about other authors' derived types.

(3)如果该方法不是私有的,您将看不到此内容.如果基类的f()具有封装或受保护的可见性,则该方法将是虚拟方法.

(3) You won't see this if the method was not private. If the base class's f() had package or protected visibility, then the method would be a virtual method.

(4)Java不支持第2点的相反操作.具体来说,如果派生类具有私有方法,并且新版本的基类型引入了具有相同签名的非私有方法,则派生类和新基类不能一起使用.还有其他语言(例如C#)可以更全面地解决这类模块化的,代际开发问题.如果您对此方面感兴趣,可以在Artima上阅读:版本,虚拟和替代

(4) The reverse of point #2 is not supported by Java. Specifically, if a derived class has a private method, and a new version of the base type introduces a non-private method with the same signature, the derived class and new base class cannot be used together. There are other languages (for example C#) that addresses these sorts of modular, generational development questions more completely. If you are interested in this aspect, this is a good read on Artima: Versioning, Virtual, and Override

这篇关于Java:为什么基类方法可以调用不存在的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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