Java:具有返回类型的继承方法

时间:2015-06-10 19:54:41

标签: java inheritance return

Class3类扩展到Class1类。在Class3中,该方法应该返回奖金的总和,并且工资和Class1继承自Class3并显示总数并通过将总数乘以12来计算年薪。问题在于输出这是我得到的总数,yearlySalary是0.0。

以下是代码:

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);
    }
}

第二课:

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

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

2 个答案:

答案 0 :(得分:5)

您永远不会致电CalcTotal()

您必须确保在计算yearlySalary值之前将其称为

答案 1 :(得分:1)

你从未调用过CalcTotal()。 试试这个:

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

        }

    }