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

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

问题描述

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

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??
    }
}

为什么允许这种行为?

推荐答案

内部类只是将真正属于原始外部类的某些功能彻底分离的一种方式.它们旨在在您有 2 个要求时使用:

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. 如果在单独的类中实现,外部类中的某些功能会最清楚.
  2. 即使它在一个单独的类中,其功能也与外部类的工作方式密切相关.

鉴于这些要求,内部类可以完全访问其外部类.由于它们基本上是外部类的成员,因此它们可以访问外部类的方法和属性——包括私有的.

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天全站免登陆