I have a question about instance variables in java classes.
I have the following class Employer.java
public class Employee {
String name = "";
public double salary = 0;
public double getEarnings() {
System.out.println("Super Earnings: " + salary);
return salary;
}
}
Here is my Manager class as a subclass of Employer:
public class Manager extends Employee {
public double bonus;
public double salary = 0;
@Override
public double getEarnings() {
return super.getEarnings() + bonus;
}
}
In the main function I try to set the bonus and I have the following code:
public class App {
public static void main(String[] args) throws Exception {
Manager myMan01 = new Manager();
myMan01.name = "Mike";
myMan01.salary = 3000;
myMan01.bonus = 2000;
System.out.println(myMan01.getEarnings());
System.out.println(myMan01.salary);
}
}
I expected the output to be 5000. But it actually is 2000.
I know I have instantiated the salary variable in the superclass and the subclass, which seems to be causing the output. I just don't understand, why myMan01.salary
is not called by super.getEarnings()
. Can anyone please clarify?
Thanks in advance and sorry for the formatting. Lots to learn, still :)