Java: Inherited class constructor is calling Super class

穿精又带淫゛_ 提交于 2019-12-01 13:44:08

The superclass doesn't have a default constructor. So you need to pass the appropriate constructor arguments to the superclass:

super(id);

(Put this as the top line in both the Manager and Engineer constructors.) You should also remove the this.emp_id = id line, in both cases.

In general, if your constructor doesn't start with a super(...) or this(...) statement (and you can only have one of these, not both), then it defaults to using super() (with no arguments).

Since you have specified a constructor with arguments, Java does not provide with a default constructor without arguments. You should create one yourself, or explicitly call the constructor you have created, by using super(id) as first line in the extended classes constructors.

The error is generated since you didn't define a default constructor (no arguments) in Employee

class Employee {

    private int emp_id;

    public Employee() {
    }

    public Employee(int id)  {
            this.emp_id = id;
    }

    public int get_id() {
            return emp_id;
    }

}

but there are a couple of points to consider: you are setting emp_id via the constructor and defined a getter to read it. It seems that the field was meant to be private. Otherwise you can just access directly.

You already have a constructor in Employee setting the ID no need to define the same constructor in the same class. Just use the constructor of the superclass.

class Manager extends Employee {

    public Manager(int id ) {
        super(id);  // calls the superclass constructor
    }

}

In this case you don't need the default constructor.

In java, a sub class constructor always calls one of its parent class's constructor. This is neccessary for the class to be initialized properly. Even when it is subclassed, the fields and state must be setup and this is how its done in java. If none is explicitly specified, it is calling the default no-arg constructor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!