[英]Why anonymous class can't access private methods and variables?
package demo;
class Child{
private static int a=50;
public void fin() {
System.out.println("hello");
}
private void fly() {
System.out.println("lol");
}
}
public class Hello {
public static void main(String[] args)
{
Child c=new Child() {
public void f() {
System.out.println("sorry"+a);
}
public void fin() {
System.out.println("hello");
}
};
c.fin();
}}
Above is the code of java my point is why cant private methods and variables be called in anonymous class as I had read somewhere that an anonymous class can access all members of enclosed class.以上是java的代码,我的观点是为什么不能在匿名类中调用私有方法和变量,因为我在某处读到匿名类可以访问封闭类的所有成员。
https://www.baeldung.com/java-anonymous-classes go checkout which specifies that each member of the anonymous class can access all members of the enclosed class. https://www.baeldung.com/java-anonymous-classes go checkout 指定匿名类的每个成员都可以访问封闭类的所有成员。
There is a confusion in that code about "inner class" and "anonymous class".该代码中关于“内部类”和“匿名类”存在混淆。
Notice you have 3 classes there:请注意,您在那里有 3 个类:
Child
Hello
Hello$1
: An anonymous class declared inside of Hello
and whose parent is Child
Hello$1
:在Hello
内部声明的匿名类,其父类是Child
The confusion in the code is about the latter:代码中的混淆是关于后者:
Hello$1
is a subclass of Child
Hello$1
是Child
的子类Hello$1
is an inner class of Hello
Hello$1
是一个内部类的Hello
This means:这意味着:
Hello$1
cannot access private fields from Child
, as subclasses cannot access private elements of their super classes Hello$1
无法从Child
访问私有字段,因为子类无法访问其超类的私有元素Hello$1
can access private fields from Hello
, as anonymous inner classes can access private elements of their enclosing classes Hello$1
可以从Hello
访问私有字段,因为匿名内部类可以访问其封闭类的私有元素Check it more clearly in this code:在此代码中更清楚地检查它:
class Child {
private int a = 50;
}
public class Hello {
private int b = 60;
public void f()
{
Child c = new Child() {
public void f() {
// System.out.println("a = " + a); // This won't compile
System.out.println("b = " + b); // This compiles OK
}
};
}
}
The fact that you're anonymously overriding class is inconsequential to the situation.您匿名覆盖类这一事实对这种情况无关紧要。 A class cannot access its parent's
private
members.类不能访问其父类的
private
成员。 If you want to access the parent's members you could define them with protected
or default visibility.如果要访问父成员的成员,可以使用
protected
或默认可见性定义它们。
i had read somewhere that anonymous class can access all members of enclosed class.
我在某处读到匿名类可以访问封闭类的所有成员。
I assume you mean of enclosing class and yes.我假设你的意思是封闭类,是的。 However
Child
is not the enclosing class it's the parent class.然而
Child
不是封闭类,它是父类。 The enclosing class in your case would be Hello.class
and if you add to it private static int a;
您的情况下的封闭类将是
Hello.class
并且如果您将其添加到private static int a;
ie: IE:
public class Hello {
private static int a = 40;
...
It will work.它会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.