简体   繁体   English

抽象类构造函数初始化

[英]Abstract class constructor initialization

I was looking simple abstraction example as follows , 我正在寻找以下简单的抽象示例,

public abstract class Employee {
    private String name;
    private String address;
    private int number;

    public Employee(String name, String address, int number) {
        System.out.println("Constructing an Employee");
        this.name = name;
        this.address = address;
        this.number = number;
    }
}

public class Salary extends Employee {
    private double salary; //Annual salary

    public Salary(String name, String address, int number, double salary) {
        super(name, address, number);
        setSalary(salary);
    }
}

public class AbstractDemo {
    public static void main(String[] args) {
        Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
        Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
    }
}

Here I have an abstract base class and concrete sub-classes. 在这里,我有一个抽象的基类和具体的子类。 The abstract class has 3 parameters in constructor and subclass has four , but when I initialize both the abstract and concrete class in the main method, both constructors are passed 4 parameters and using setSalary() method I am able to calculate a salary for both s and e even thought the Employee abstract class only takes 3 parameters. 抽象类在构造函数中有3个参数,子类有4个参数 ,但是当我在main方法中初始化抽象类和具体类时,两个构造函数都传递了4个参数,并且使用setSalary()方法,我可以为两个s计算薪水e甚至认为Employee抽象类仅接受3个参数。

How is this happening? 这是怎么回事? Could someone please help me with this? 有人可以帮我吗?

I'm not sure I understand what you're saying about computesalary() (which isn't in your sample code), but I suspect the confusion might be about this line: 我不确定我是否理解您在说什么computesalary() (您的示例代码中没有),但是我怀疑这可能与以下内容有关:

Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);

Here, note that even though you're assigning the reference to a variable of type Employee , you're still creating a Salary object. 在这里,请注意,即使您将引用分配给Employee类型的变量,您仍在创建Salary对象。 Therefore you still call the Salary derived class' constructor, which has 4 arguments. 因此,您仍然调用Salary派生类的构造函数,该构造函数具有4个参数。 This line of code is doing exactly the same thing as the line above it, and executing exactly the same code path. 此代码行与上面的代码行完全相同,并且执行完全相同的代码路径。 The only difference is that the reference to the newly-created object gets stored in a variable with the base class' type. 唯一的区别是对新创建对象的引用存储在具有基类类型的变量中。

As Thomas points out, this would call the base class 3-argument constructor: 正如Thomas指出的那样, 将调用基类3参数构造函数:

Employee e = new Employee("John Adams", "Boston, MA", 2);

But this wouldn't be valid code since Employee is abstract. 但这不是有效的代码,因为Employee是抽象的。

在这两种情况下,您都将创建Salary类的实例,因此被调用的构造函数来自Salary类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM