Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
970 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...