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

查看:28
本文介绍了在继承的类中使用私有变量 - 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 不能直接访问它.仅通过使用类 A 中定义的公共/默认/受保护访问器方法.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天全站免登陆