Search code examples
javainheritanceconstructorsubclasssuperclass

Java: Inherited class constructor is calling Super class


While creating a java program i encountered a problem,

A subclass constructor is throwing an Error by calling the Superclass's method

The code is similar to this :

class Manage
{
    public static void main(String[] args) 
    {
        Manager m1 = new Manager ( 35 );
    }
}

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

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

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

And the error is something like this :

$ javac app.java 
app.java:25: cannot find symbol
symbol  : constructor Employee()
location: class Employee
        {
        ^
app.java:33: cannot find symbol
symbol  : constructor Employee()
location: class Employee
        {
        ^
2 errors

Why does this happen ?


Solution

  • 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).