为什么外部Java类可以访问内部类的私有成员? [英] Why can outer Java classes access inner class private members?

查看:286
本文介绍了为什么外部Java类可以访问内部类的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观察到外层类可以访问内部类私有实例变量。这怎么可能?这里是一个示例代码演示相同:

  class ABC {
class XYZ {
private int x = 10;
}

public static void main(String ... args){
ABC.XYZ xx = new ABC()。new XYZ();
System.out.println(Hello ::+ xx.x); ///为什么这允许?
}
}

为什么允许此行为?

解决方案

内部类只是一种干净地分离一些真正属于原始外部类的功能的方法。它们用于在您有两个要求时使用:


  1. 您的外部类中的一些功能将是最清楚的,如果它实现



根据这些要求,内部类可以完全访问它们的外部类。因为它们基本上是外部类的成员,所以他们可以访问外部类的方法和属性(包括privates)是有意义的。


I observed that Outer classes can access inner classes private instance variables. How is this possible? Here is a sample code demonstrating the same:

class ABC{
    class XYZ{
        private int x=10;
    }

    public static void main(String... args){
        ABC.XYZ xx = new ABC().new XYZ();
        System.out.println("Hello :: "+xx.x); ///Why is this allowed??
    }
}

Why is this behavior allowed?

解决方案

The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class. They are intended to be used when you have 2 requirements:

  1. Some piece of functionality in your outer class would be most clear if it was implemented in a separate class.
  2. Even though it's in a separate class, the functionality is very closely tied to way that the outer class works.

Given these requirements, inner classes have full access to their outer class. Since they're basically a member of the outer class, it makes sense that they have access to methods and attributes of the outer class -- including privates.

这篇关于为什么外部Java类可以访问内部类的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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