[英]java anoymous class can access private member of outer class. Why this code cannot access private data member?
I want to access private member of a class by anonymous class created in a different class.我想通过在不同类中创建的匿名类访问类的私有成员。 I am new to java, kindly please explain this and tell what i am doing wrong.我是java新手,请解释一下并告诉我做错了什么。
class movie{
private String moviename="bahubali";
void display(){
System.out.println(moviename);
}
}
public class InnerClass{ //main class
public static void main(String[] args) {
movie anonymous=new movie() {
void display() {
System.out.println(moviename+" in anonymous class");
}
};
anonymous.display();
}
}
Your anonymous class inherits from the class movie
(you should make it Movie
instead btw. to comply with Java standards).您的匿名类继承自movie
类(您应该将其改为Movie
以符合 Java 标准)。
Inheriting classes are granted access to protected
members, not to private
members.继承类被授予对protected
成员的访问权限,而不是对private
成员的访问权限。
So the fix in this case should be changing所以在这种情况下的修复应该改变
private String moviename="bahubali";
to到
protected String moviename="bahubali";
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.