The super
keyword in a subclass (Savings
) is not referring to the Account
class. I am trying to reference the total instance of the Account
class by using super.total
, however it is giving me the total of the Savings
class.
total
and super.total
are the same. Furthermore, when I print out super.getClass()
in the console, it gives me the subclass (Savings
) instead of the super class (Accounts
).
Savings.java
public class Savings extends Account {
public Savings(int initial, User owner, double history, double monthInterest) {
super(initial, owner);
int total = getTotal();
deposit(history * 12 * monthInterest / 100 * (total 55),
"monthly interest",
"Total interest accumulated in " Math.round(history * 12) " months");
}
public void transferS(int amount) {
System.out.println(total);
System.out.println(super.total);
}
Account.java
public class Account {
private User owner;
protected int total;
public Account(int initial, User owner) {
this.total = initial;
this.owner = owner;
}
public int getTotal() {
return total;
}
CodePudding user response:
You didn't define any total
property in your derived class (Savings
), thus when accessing total
you get the property defined only in the base class Account
(there is no alternative in your implementation of Savings
). If you need to introduce distinct properties used between base and derived classes with the same name, define a new property with the same name in the derived class, like this:
public class Savings extends Account {
int total;
...
With this implementation you'll get two different variables total
and super.total
which store different values.