如何解决超类的私有方法? [英] How private method of super class are resolved?

查看:105
本文介绍了如何解决超类的私有方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class A{ 
  private void sayA(){
     System.out.println("Private method of A");
  }
  public static void main(String args[]){
      A instanceA=new B();
      instanceA.sayA();
  }
}

class B extends A{
}

我原本期望它在编译时抛出一个运行时异常,编译器会检查 sayA()是否可以在 A 并且在运行时它会检查是否可以在 B上调用sayA() 的对象。但它改为打印 A 的私人方法。

I was expecting it to throw a run time exception as at compile-time the compiler checks if sayA() can be called on a reference of A and at run-time it'll check if sayA() can be called on B's object. But it instead printed "Private method of A".

推荐答案

可访问性是编译时的概念(反映在Reflection API中)。

Accessibility is a compile time concept (reflected in Reflection APIs).

来自Java语言规范


请注意,可访问性是一个静态属性,可以在
编译时确定;它仅取决于类型和声明修饰符。

Note that accessibility is a static property that can be determined at compile time; it depends only on types and declaration modifiers.

也就是说,编译器不关心引用的实例的运行时类型是什么名为 instanceA 的变量将

That is, the compiler doesn't care what the runtime type of the instance referenced by your variable named instanceA will be

A instanceA = new B();

它只关心你在静态类型 A的引用上调用了一个方法。该方法是 private ,因为你在声明它的类的主体内,它是可见的,因此可用。

It only cares that you invoked a method on a reference of static type A. That method is private and since you are within the body of the class which declares it, it is visible, and therefore usable.


否则,成员或构造函数被声明为private,并且当且仅当它出现在顶级
类的主体内时才允许访问
(第7.6节) )包含成员的声明或
构造函数。

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.






For spiderman在评论中,请考虑以下内容


For spiderman in comments, consider the following

class A {
    private void privateMethod () {
        System.out.println("private method");
    }
    public void publicMethod() {
        privateMethod();
    }
}

class B extends A {}

class Example {
    public static void main(String[] args) {
        new B().publicMethod();
    }
}

这篇关于如何解决超类的私有方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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