The following is my ProtectedConstructor.java
source code:
package protectCon;
public class ProtectedConstructor{
public int nothing;
ProtectedConstructor(){
nothing = 0;
}
}
And following is the UsingProtectedCon.java
source:
package other;
import protectcon.ProtectedConstructor;
public class UsingProtectedCon extends ProtectedConstructor{ //**Line 4**
public static void main(String... a) {
}
}
When I compile UsingProtectedCon.java
, I get error at Line 4 shown above. It says that ProtectedConstructor() is not public ; so cannot be accessed outside package.
However, since my class is public, shouldn't I be able to extend it outside package. I am anyway not creating any instance of it.
Now, if I make the constructor of ProtectedConstructor
class as public
or protected
then the code compiles fine with no error.
So then why is it necessary even for the constructor to be public
or protected
, and not just have default access?
to avoid all confusion do it like this. package protectCon;
JLS 6.6.7 answers your question. A subclass only access a protected members of its parent class, if it involves implementation of its parent. Therefore , you can not instantiate a parent object in a child class, if parent constructor is protected and it is in different package.Since the default constructor of the subclass would try to call parent class constructor ,you got this error.
See this SO Post for details
in your class ProtectedConstructor is defined with Package-Private access This means that outside the package its not seen even by the classes that extend from your ProtectedConstructor class
Define your constructor with 'protected' access modifier instead and you'll be done:
Your constructor is not public. Default scope is package-private.
If child will have constructor which is private in parent,we can make child's instance with that constructor and cast it to parent's type. So to prevent this java compiler is not allowing constructor to have constructor which is private in parent.
constructor
is a member of class likefield
andmethod
so access modifier applies to it in the same manner it apples to all the member of classwhen you extend the class A in B , A's its default constructor will get called from B's constructor implicitly (if you don't call any of the overloaded constructor)