Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor of subclass in Java

When compiling this program, I get error-

 class Person {
    Person(int a) { }
 }
 class Employee extends Person {
    Employee(int b) { }
 }
 public class A1{
    public static void main(String[] args){ }
 }

Error- Cannot find Constructor Person(). Why defining Person() is necessary?

like image 545
Naman Avatar asked Mar 06 '12 15:03

Naman


3 Answers

When creating an Employee you're creating a Person at the same time. To make sure the Person is properly constructed, the compiler adds an implicit call to super() in the Employee constructor:

 class Employee extends Person {
     Employee(int id) {
         super();          // implicitly added by the compiler.
     }
 }

Since Person does not have a no-argument constructor this fails.

You solve it by either

  • adding an explicit call to super, like this:

     class Employee extends Person {
         Employee(int id) {
             super(id);
         }
     }
    
  • or by adding a no-arg constructor to Person:

    class Person {
        Person() {
        }
    
        Person(int a) {
        }
    }
    

Usually a no-arg constructor is also implicitly added by the compiler. As Binyamin Sharet points out in the comments however, this is only the case if no constructor is specified at all. In your case, you have specified a Person constructor, thus no implicit constructor is created.

like image 160
aioobe Avatar answered Sep 18 '22 17:09

aioobe


The constructor for Employee doesn't know how to construct the super-class, Person. Without you explicitly telling it, it will default to trying the no-args constructor of the super-class, which doesn't exist. Hence the error.

The fix is:

class Employee extends person {
    public Employee(int id) {
        super(id);
    }
}
like image 41
dty Avatar answered Sep 21 '22 17:09

dty


Java actually views this code as:

class Person {
  Person(int nm) { }
 }
 class Employee extends Person {
    Employee(int id) {
        super();
    }
 }
 public class EmployeeTest1 {
    public static void main(String[] args){ }
 }

Since there is no Person() constructor this fails. Instead try:

class Person {
  Person(int nm) { }
 }
 class Employee extends Person {
    Employee(int id) {
        super(id);
    }
 }
 public class EmployeeTest1 {
    public static void main(String[] args){ }
 }
like image 45
Jim Avatar answered Sep 20 '22 17:09

Jim