![](/img/trans.png)
[英]How does the subclass object access the private variable of super class,as in java no except the class itself can access the private variable?
[英]How can this keyword access private members of class while object of class itself can not
我对此关键字的概念有些疑问,让我向您展示一个示例,我可以通过该示例进行解释
public class InheritanceInJava
{
public static void main(String args[])
{
A obj = new A(4,5);
obj.num3 = 4; //using object to access private member of class which is not possible
}
class A
{
private int num1;
private int num2;
private int num3;
A(int num1, int num2)
{
this.num1 = num1; //this keyword can access num1 in order initalize value
this.num2 = num2;
}
}
现在,根据this 关键字的定义,可以使用this 关键字从实例方法或构造函数中引用当前对象的任何成员。
由于这是对当前对象的引用,通过该方法调用方法或构造函数,并且由于类本身的对象无法访问类的私有成员,因此该关键字如何访问它?
如果我们看上面的例子:
this-> obj //此引用当前对象,该对象调用构造函数或方法
如果obj.num3 = 4或obj.num1 = 6无效,那么this.num1 = num1如何有效?
private
访问修饰符将那些变量的访问限制在顶级类内部。 既然你调用this
从顶层类中(你必须),您可以访问这些变量。
我说的是“顶级”类,而不仅仅是覆盖嵌套类的类(外部类可以访问其内部类的私有字段)。
根据java docs https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html :
private修饰符指定只能在其自己的类中访问该成员。
您需要记住,如果对象是在类中使用创建的,则它可以从类中使用很好地访问私有数据,私有公共限制不适用于同一类的成员。
在定义私有变量的类中定义了“ A”构造函数。 您的代码说的是:
“有一个带有私有变量的'A'类(只有'A'可以访问它们。)在'A'类之外构造时,'A'对象可以给予临时许可来更改那些私有变量,因为这是在构造函数中定义。在此之后的任何时间,这些私有变量都无法更改。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.