gpt4 book ai didi

java私有(private)访问修饰符可以在类之外访问吗?

转载 作者:行者123 更新时间:2023-12-02 00:26:01 25 4
gpt4 key购买 nike

为什么java编译器不限制访问其他类的私有(private)属性?我有一个内部类,它有一个属性“a”和修饰符“private”。我可以在类之外使用其实例变量访问该变量。请参阅下面的代码。

package com.test;

public class Test {

public Test() {
}

public static void main(String[] args) {
new Test().execute(); // test method
}

public void execute() {
InnerClass innerClassInstance = new InnerClass();
// accessing private member from other class instance, HOW?
System.out.println(innerClassInstance.a);

InnerStaticClass innerStaticClassInstance = new InnerStaticClass();
// accessing private member from other class instance, HOW?
System.out.println(innerStaticClassInstance.a);
}

private final class InnerClass {
private int a; // accessible only in InnerClass??
}

private final static class InnerStaticClass {
private int a; // accessible only in InnerClass??
}
}

最佳答案

<罢工>

<罢工>

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private

http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

<罢工>

抱歉,我看错了问题。

查看 JLS http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1

Otherwise, if the member or constructor is declared private, then 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.

因此,内部类中的字段(显然位于类体内)可以被外部类访问,即使它是私有(private)的。

关于java私有(private)访问修饰符可以在类之外访问吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10041449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com