This question already has an answer here:
Why can't I use protected constructors outside the package for this piece of code:
package code;
public class Example{
protected Example(){}
...
}
Check.java
package test;
public class Check extends Example {
void m1() {
Example ex=new Example(); //compilation error
}
}
- Why do i get the error even though i have extended the class? Please explain
EDIT:
Compilation error:
The constructor Example() is not visible
protected modifier is used only with in the package and in sub-classes outside the package. When you create a object using
Example ex=new Example();
it will call parent class constructor by default.As parent class constructor being protected you are getting a compile time error. You need to call the protected constructor according to JSL 6.6.2.2 as shown below in example 2.
Example 2 conforming to JLS 6.6.2.2:
Usually
protected
means only accessible to subclasses or classes in the same package. However here are the rules for constructors from the JLS:As an example, this does not compile
but this does
and so does this
So the rules are clear, but I can't say I understand the reasons behind them!
In fact you are already using protected constructor of Example because Check has an implicit constructor and implicit Example constructor call: