[英]How to access private data member outside the class?
I am trying to access the private data member of inner class outside the outer class. 我正在尝试在外部类之外访问内部类的私有数据成员。
Please help me? 请帮我?
You don't - that's the whole point of it being private. 您不需要-这就是私有化的全部意义。
The inner class can expose the data via a property, of course: 内部类当然可以通过属性公开数据:
public class Outer {
public class Inner {
private final String name;
public Inner(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
}
public class Other {
public void foo() {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner("Foo");
// Can't access inner.name here...
System.out.println(inner.getName()); // But can call getName
}
}
... but if the inner class wants to keep it private, then you shouldn't try to access it. ...但是,如果内部类希望将其保持私有,那么您不应该尝试访问它。
Create public getter setter methods inside the inner class for private variables. 在内部类中为私有变量创建公共getter setter方法。 Then create an object and call them to access private data. 然后创建一个对象并调用它们以访问私有数据。 You can't directly access private data. 您不能直接访问私人数据。
you cant access a private data. 您无法访问私人数据。 If ýou have other thoughts of accessing it use public getter method returning that private data. 如果您有其他访问想法,请使用公共获取方法返回该私有数据。
you can access private data member using getter method ex 您可以使用getter方法ex访问私有数据成员
package pack;
import java.io.ObjectInputStream.GetField;
public class abc {
private int num = 2;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
class otherClass {
public static void main(String[] args) {
abc obj = new abc();
System.out.println(obj.getNum());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.