[英]How do I use the a private instance variable in a superclass?
I am currently learning about inheritance in my java class. 我目前正在Java类中学习有关继承的知识。 And I can't figure out why I can't use the variable "ID" using super in my subclass.
而且我无法弄清楚为什么不能在子类中使用super来使用变量“ ID”。 What is wrong with my constructor for the savings class?
我的储蓄类构造函数有什么问题? Also I am not allowed to change the instance variables in account to public.
另外,我也不允许将帐户中的实例变量更改为public。
public class Account
{
private String ID;
private double balance;
private int deposits;
private int withdrawals;
private double service;
/**
* Constructor for objects of class Account
*/
public Account(String IDNumber, double cashBalance)
{
ID = IDNumber;
balance = cashBalance;
deposits = 0;
withdrawals = 0;
service = 0;
}
I get the error "ID has private access in Account" 我收到错误消息“ ID在帐户中具有私人访问权限”
public class Savings extends Account
{
// instance variables - replace the example below with your own
private boolean active;
/**
* Constructor for objects of class Savings
*/
public Savings(String IDNumber, double cashBalance)
{
super(ID);
super(balance);
active = null;
}
super()
calls the constructor for the parent class. super()
调用父类的构造函数。 It has nothing to do with the private variable for that class. 它与该类的私有变量无关。
I think you ment to do: 我认为您愿意:
super(IDNumber, cashBalance);
This calls the constructor for the parent class, passing the same variables Savings
was created with to the Account
class. 这将调用父类的构造函数,将与创建
Savings
相同的变量传递给Account
类。
Note that from within the class Savings
you will not be able to access the parent variables. 请注意,在“
Savings
”类中,您将无法访问父变量。 You have to change the access to protected
for this. 为此,您必须将访问权限更改为
protected
。 protected
allows the class itself, and children access, whereas private
only allows the class itself access. protected
允许类本身和子级访问,而private
只允许类本身访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.