在继承的类中使用私有变量 - Java [英] Using a private variable in a inherited class - Java

查看:70
本文介绍了在继承的类中使用私有变量 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要对私有变量和继承有更多的了解。之前我的理解是,如果一个类中有字段,并且当我继承该类时,不受访问限制的字段(私有变量)将存在于继承的类中。但是如果有一个公共g / setter方法,我可以在基类中使用私有变量。

Need to have more understanding about the private variables and inheritance. Earlier my understanding was if there is field in a class and when I'm inheriting the class, the fields that is not restricted by access(private variables) will be there in the inherited class. But I'm able use the private variables in base class if there is a public g/setter method.

我怎样才能想象一个基类中的私有变量。

How can I imagine a private variable in a base class.?

推荐答案

class A {
  private int a;
  public A(int a) { this.a = a; }
  public int getA() {return a;}
}

class B extends A {
  public B(int b) { super(b); }
  public int getB() {return getA();}
}

int result = new B(10).getA();

结果将是10. A类中的私有字段a是继承到B但是B可以' t直接访问它。只能使用A类中定义的public / default / protected访问器方法.B是A所以它总是具有A中所有相同的字段,并且可能在B类中定义一些新字段。

result will be 10. Private field a in class A is kind of inherited to B but B can't access it directly. Only by using the public/default/protected accessor methods defined in class A. B is A so it always has all the same fields that are in A and possible some new fields defined in class B.

这篇关于在继承的类中使用私有变量 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆