Java: Inheriting method with return type

86 views Asked by At

The Class3 class extends to Class1 class. In Class3, the method should return the total of the bonus and the salary and Class1 inherits from Class3 and displays the total and calculates the yearly salary by multiplying the total by 12. The problem is that the output which is I am getting for the total and yearlySalary is 0.0.

Here are the codes:

class MyClass extends MyClass3{
    double yearlySalary = 12.0*total;

    public static void main(String[] args) {
        MyClass obj1 = new MyClass();

        System.out.println("Employee's salary is: "+ obj1.salary);
        System.out.println("Employee's bonus is: "+ obj1.bonus);
        System.out.println("Total: "+ obj1.total);
        System.out.println("Yearly Salary: "+ obj1.yearlySalary);
    }
}

Second class:

public class MyClass3 { 
    double salary =40000;
    double bonus = 2000;
    double total;       

    public double CalcTotal(){
        total = salary+bonus;
        return total;
    }
}
2

There are 2 answers

0
NilZzz On BEST ANSWER

You never called CalcTotal(). Try this:

class MyClass extends MyClass3{


        double yearlySalary= 12.0*CalcTotal();

        public static void main(String[] args) {

         MyClass obj1= new MyClass();



         System.out.println("Employee's salary is: "+ obj1.salary);
         System.out.println("Employee's bonus is: "+ obj1.bonus);
         System.out.println("Total: "+ obj1.total);
         System.out.println("Yearly Salary: "+ obj1.yearlySalary);

        }

    }
0
Alnitak On

You never call CalcTotal().

You must also ensure that you call it before the yearlySalary value is calculated.