Java - 为什么child没有继承父变量?

时间:2017-10-15 03:48:56

标签: java inheritance polymorphism parent-child parent

为什么运行此代码时会得到0而不是1500?

public class Department {
    private double rate = 0.0;

    public Department {
    }

    public getRate(){
        return rate;
    }

    public setRate(){
        rate = 1 + 2;
    }
}

public class Employe extends Department {

    private double salary = 0;

    public Employe {
    }

    public calculateSalary(){
          salary = getRate() * 500;
    }
}

public static void main(String[] args) throws IOException {

    Department department = New Department();
    department.setRate();

    Employe employe = new Employe();
    System.out.println(employe.calculateSalary());
}

2 个答案:

答案 0 :(得分:0)

您创建了Department,然后将其rate设置为3。 然后你创建了一个Employee,没有设置它的速率,所以它的rate为0.

当你说new时,你会得到一个全新的对象。要获得您想要的内容,请将代码更改为:

Employee employee = New Department();
employee.setRate();
System.out.println(employe.calculateSalary());

你的整个代码很奇怪,一个部门有员工。员工不是一种部门。我们使用extends来表示X是一种Y.

答案 1 :(得分:0)

孩子确实继承了父变量。但是,部门和员工是不同的对象,所以他们不分享变量。请尝试以下代码:

Employe employe = new Employe();
employe.setRate();
System.out.println(employe.calculateSalary());