I’m just having some trouble in Java with a specific error, and none of my research has come up with a solution.
I have two classes, Employee and Executive. Employee is initialised as:
public abstract class Employee{
protected String name;
protected double wage;
public Employee(String name, double wage){
this.name = name;
this.wage = wage;
}
With a few get functions following. Executive is initialised as:
public class Executive extends Employee{
double annualBonus;
public Executive(String name, double wage, double annualBonus){
super.name = name;
super.wage = wage;
this.annualBonus = annualBonus;
}
However this is throwing the error: "actual and formal argument lists differ in length"
Executive.java:6: error: constructor Employee in class Employee cannot be applied to given types;
public Executive(String name, double wage, double annualBonus){
^
required: String,double
found: no arguments
reason: actual and formal argument lists differ in length
8 errors
[ERROR] Build errors detected!
From all of my research this error is thrown when there is a mismatched number of arguments or the constructor is coded incorrectly, however to the best of my knowledge I can’t see what is wrong here. While the parent class has one less argument than the child class, I saw that an issue like this could be solved using the base keyword and I tried this solution as:
public Executive(String name, double wage, double annualBonus) base:(String name, double wage){
super.name = name;
super.wage = wage;
this.annualBonus = annualBonus;
}
However this throws a different error:
Executive.java:6: error: missing method body, or declare abstract
public Executive(String name, double wage, double annualBonus) base:(String name, double wage){
^
I know the solution here is probably really obvious but I’ve been trying at it and can’t seem to crack this. Any help will be greatly appreciated!
>Solution :
It is because you should not use assignment to assign protected values manually, instead, in the start of your constructor, you should leverage the constructor from you inherited parent super(...);.
Here is a link explaining why we should put the super() and this() in the first line of the constructor when parent’s constructor takes parameter. https://stackoverflow.com/a/1168356/6346643
In this example, the proper manner to inherit class Employee should be:
public class Executive extends Employee {
double annualBonus;
public Executive(String name, double wage, double annualBonus) {
super(name, wage);
this.annualBonus = annualBonus;
}
}