Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor
Any constructor for any class as you know creates an object. So, the constructor should contain proper initialization code for its class. But if you have some class which extends another one (lets call it "parent") then constructor for the class cannot contain all the code needed for the initialization by definition (for example, you cannot define private fields of the parent). That's why constructor of the class has to call constructor of its parent. If you do not call it explicitly then the default parent constructor is called (which is without any parameter).
So, in your case, you can either implement default constructor in parent or directly call any constructor in the class.
As others have already mentioned you are required to provide a default constructor public Employee(){}
in your Employee
class.
What happens is that the compiler automatically provides a no-argument, default constructor for any class without constructors. If your class has no explicit superclass, then it has an implicit superclass of Object
, which does have a no-argument constructor. In this case you are declaring a constructor in your class Employee
therefore you must provide also the no-argument constructor.
Having said that Employee
class should look like this:
Your class Employee
import java.util.Date;
public class Employee
{
private String name, number;
private Date date;
public Employee(){} // No-argument Constructor
public Employee(String name, String number, Date date)
{
setName(name);
setNumber(number);
setDate(date);
}
public void setName(String n)
{
name = n;
}
public void setNumber(String n)
{
number = n;
// you can check the format here for correctness
}
public void setDate(Date d)
{
date = d;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public Date getDate()
{
return date;
}
}
Here is the Java Oracle tutorial - Providing Constructors for Your Classes chapter. Go through it and you will have a clearer idea of what is going on.
ProductionWorker
extends Employee
, thus it is said that it has all the capabilities of an Employee. In order to accomplish that, Java automatically puts a super();
call in each constructor's first line, you can put it manually but usually it is not necessary. In your case, it is necessary because the call to super();
cannot be placed automatically due to the fact that Employee's constructor has parameters.
You either need to define a default constructor in your Employee
class, or call super('Erkan', 21, new Date());
in the first line of the constructor in ProductionWorker.