是否需要在私有内部类中声明访问修饰符 [英] Is there a need to declare access modifiers in a private inner class

查看:129
本文介绍了是否需要在私有内部类中声明访问修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有一个这样的课程:

Let's say I have a class like this:

public class OuterClass {
  //...
  private class InnerClass {
     private int x; // This variable makes sense
     public int y; // Is there any use for this?
  }
}

在上面的代码中,由于内部类是私有的,只有外部类才能访问其所有变量,甚至是私有变量。内部类本身对周围的外部类是不可见的。

In the code above, since the inner class is private, only the outer class has access to all its variables, even the private ones. The inner class itself is not visible to any other class but the enclosing outer class.

因此,即使变量 y 上面的是公共的,除外部类外,任何其他类都不能访问它。

So even though variable y above is public, it cannot be accessed by any other class other than the outer class.

私有内部类中的所有访问修饰符似乎默认都是私有的,不是吗?

It would seem all access modifiers in the private inner class are by default private, aren't they?

因此,有没有理由为内部类的任何成员声明访问修饰符?

So given that, is there any reason to declare access modifiers at all for any of the members of the inner class?

推荐答案

访问修饰符可能对覆盖超类方法的方法(例如toString())有效的情况。您无法降低覆盖方法的可见性。为了使该类能够编译,必须始终将toString()声明为公共。

Case where the access modifier may matter are for methods that override a superclass method(e.g. toString()). You can not reduce the visibility of an overridden method. toString() must always be declared public in order for the class to compile.

当外部类访问私有成员时,编译器将创建一个合成方法。这种综合方法仅在嵌套类的.class文件中可见。

When private members are accessed by the outer class, the compiler creates a synthetic method. This synthetic method is only visible in the .class file of the nested class.

另一种情况是,当内部类本身不是私有的时,访问修饰符作用域很重要。

Another case when access modifier scope matters when the inner class itself is not private.

这篇关于是否需要在私有内部类中声明访问修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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