The following code gives a compilation error:
class parent {
parent(int a){}
}
class child extends parent{}
Error:
Main.java:6: cannot find symbol
symbol : constructor parent()
location: class parent
class child extends parent{}
^
1 error
I was trying to do different things and found that adding a return type to the parent constructor got rid of the error!!!
class parent {
int parent(int a){}
}
class child extends parent{}
I’ve read that constructors should not have return type, which clearly is not correct all the times. So my question is when should we have return type for constructor?
On constructor not having return type
Constructor must not have a return type. By definition, if a method has a return type, it’s not a constructor.
On default constructors
The following snippet does give a compilation error:
The reason is not because of a return type in a constructor, but because since you did not provide ANY constructor for
Child, a default constructor is automatically created for you by the compiler. However, this default constructor tries to invoke the default constructor of the superclassParent, which does NOT have a default constructor. THAT’S the source fo the compilation error.Here’s the specification for the default constructor:
The following is a simple fix:
On methods having the same name as the constructor
The following snippet DOES compile:
There is in fact no explicit constructor in the above snippet. What you have is a regular method that has the same name as the class. This is allowed, but discouraged:
You will find that if you create a
new Parent()or anew Child(),"Yipppee!!!"will NOT be printed to standard output. The method is not invoked upon creation since it’s not a constructor.