1

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.

     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"

    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;
}
kami
  • 21
  • 3
  • http://stackoverflow.com/q/4716040 – Dave Newton May 15 '17 at 01:32
  • 2
    `super(...)` doesn't mean "set this instance variable from the superclass"; it means "call a specific superclass constructor, passing these arguments". – user2357112 May 15 '17 at 01:32
  • 1
    Private has meaning-the JLS explains all of this in great detail. Nutshell is that private means absolutely that: it's private. And in your example ID doesn't even have a value anyway, so calling a super constructor that doesn't exist with a value that isn't accessible makes little to no sense. – Dave Newton May 15 '17 at 01:33

1 Answers1

2

super() calls the constructor for the parent class. 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.

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.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96