如何在超类中使用私有实例变量?

时间:2021-01-27 22:56:25

I am currently learning about inheritance in my java class. And I can't figure out why I can't use the variable "ID" using super in my subclass. What is wrong with my constructor for the savings class? Also I am not allowed to change the instance variables in account to public.

我目前正在学习java类中的继承。我无法弄清楚为什么我不能在我的子类中使用super变量“ID”。我的储蓄类构造函数出了什么问题?此外,我不允许将帐户中的实例变量更改为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;
}

1 个解决方案

#1


2  

super() calls the constructor for the parent class. It has nothing to do with the private variable for that class.

super()调用父类的构造函数。它与该类的私有变量无关。

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. You have to change the access to protected for this. protected allows the class itself, and children access, whereas private only allows the class itself access.

请注意,在类Savings中,您将无法访问父变量。您必须为此更改受保护的访问权限。 protected允许类本身和子级访问,而private只允许类本身访问。

#1


2  

super() calls the constructor for the parent class. It has nothing to do with the private variable for that class.

super()调用父类的构造函数。它与该类的私有变量无关。

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. You have to change the access to protected for this. protected allows the class itself, and children access, whereas private only allows the class itself access.

请注意,在类Savings中,您将无法访问父变量。您必须为此更改受保护的访问权限。 protected允许类本身和子级访问,而private只允许类本身访问。