0
package 1;
public class Father{
  protected Father(){
    System.out.println("This is Father");
  }
  protected void print(){
    System.out.println("This is print() from Father")
  }
}

package 2;
import 1.Father;
public class Son extends Father{
  Son(){
    System.out.println("This is Son");
    print();
    Father father = new Father();   //Error:The constructor Father() is not visible
  }
public static void main(String args[]){
    Son son = new Son();                   
}

I understand that, since they are not in the same package, protected method can only be seen in an extending class(here Son), but why a protected method print() can be called while protected constructor can not?

EDIT: I kind of get logic behind this. protected is seen either (1)in the same package or (2) child class in other package. Now when I call new Father(),error comes:

For (1) new Father() is not called in the same package. Error! For (2) Since constructor is not inherited, there is no parent constructor existing in child class. Error!

So we can use super() to refer to the constructor in parent class, which is a fix method for case(2).(There is no way to fix (1) because I already put parent class and child class into 2 different packages!OK...There is one way, change protected to public, which is too obvious to see)

kahofanfan
  • 297
  • 2
  • 11
  • 1
    Actually, that is not a good dup link. The linked question is about access to protected members. A constructor is not a member ... and the access rules are **different** for constructors. (I learned something today!) – Stephen C May 29 '15 at 23:31
  • This (http://stackoverflow.com/questions/5150748/protected-constructor-and-accessibility) would a better Q&A ... except that the "best" answer gives an incorrect explanation. – Stephen C May 29 '15 at 23:35
  • @StephenC You're right. Please update as appropriate. – Sotirios Delimanolis May 30 '15 at 00:01
  • *"(There is no way to fix (1) because I already put parent class and child class into 2 packages!)"* - Two ways. 1) change the packaging. 2) make the constructor for `Father` public. But apart from that, you can't violate the JLS rules. (See linked Q&A and specifically the answer by @mazaneicha) – Stephen C May 30 '15 at 00:25
  • @Stephe C Thanks...So am I right about where error comes? – kahofanfan May 30 '15 at 00:27
  • Not exactly. The >>real<< reason is that the JLS explicitly forbids this. The real rationale for the JLS rules is not spelled out in the JLS, but your attempt does not convince me. :-) – Stephen C May 30 '15 at 00:33
  • @Stephen C OK, I get it! I can't argue over "explicitly forbids" . – kahofanfan May 30 '15 at 00:39

0 Answers0