Constructor of Java subclass
•
Java
When compiling this program, I get an error –
class Person { Person(int a) { } } class Employee extends Person { Employee(int b) { } } public class A1{ public static void main(String[] args){ } }
Error - constructor person() not found Why is it necessary to define person()?
Solution
When you create an employee, you also create a person To ensure the correct construction of person, 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. } }
Person failed because it does not have a parameterless constructor
You can solve it
>Add an explicit call to super as follows:
class Employee extends Person { Employee(int id) { super(id); } }
>Or add a no Arg constructor to person:
class Person { Person() { } Person(int a) { } }
Usually, the compiler also implicitly adds a no - Arg constructor As Binyamin SHARET pointed out in his comments, this happens only if no constructor is specified In your case, you have specified the person constructor, so the implicit constructor will not be created
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码