2

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 :)

Jakob G
  • 21
  • 5

3 Answers3

1

In your getEarnings() method in your Manager class I think you have a typo, you return result + bonus instead of salary + bonus !

And you don't need the salary variable, it is inherited from the Employee class.

Ruchiha
  • 69
  • 7
1

There is no variable called result in your code. I think you made a typo there.

public class Manager extends Employee {
    public double bonus;
    public double salary = 0;

    @Override
    public double getEarnings() {
        return this.salary + this.bonus;
    }
}

It is always good to make instance variables private access modifier and use getter & setter methods for each variable to associate with them. (Encapsulation in OOP)

Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
0

To mark the question as answered, I will recite some comments.

The answer to this problem seems to be polymorphism (although as a beginner I have to wait to later chapters in my textbook to fully understand).

  • The problem you have here is called shadowing. You have two entirely separate fields both named salary. – chrylis -cautiouslyoptimistic- 1 hour ago

  • Possible duplicate of Hiding Fields in Java Inheritance

As stated by the comments of chrylis -cautiouslyoptimistic- and Joe.

Jakob G
  • 21
  • 5