I am clear with using private, default and public access modifiers on a public class's constructor.
If constructor is private, the class object can be created in that class only.
If constructor is default, the class object can be created in that package's classes only.
If constructor is public, the class object can be created in any class.
I am not clear with protected Constructor. Example:
Default Constructor
package com.test;
public class PracticeParent {
PracticeParent(){ //Constructor with default access modifier
System.out.println("PracticeParent default constructor");
}
}
package com.moreTest;
import com.test.PracticeParent;
public class Test extends PracticeParent { //Error. Implicit super constructor PracticeParent() is not visible for default constructor. Must define an explicit constructor
public static void main(String[] args) {
PracticeParent pp=new PracticeParent(); //Error. The constructor PracticeParent() is not visible
}
}
I understand these errors. Since the ParentPractice class is in other package and its constructor is default, it is not visible to Test class default constructor which call super() implicitly. Also, its object can't be created due to non visibility of constructor.
Protected Constructor
But with class Test extending ParentPractice and ParentPractice having protected constructor, there is no first error i.e. error in calling super() implicitly from Test's default constructor. Implicit super constructor PracticeParent() is visible for Test's default constructor but PracticeParent object can not be created. Error is shown that the constructor PracticeParent() is not visible.
package com.test;
public class PracticeParent {
protected PracticeParent(){ //Constructor with protected access modifier
System.out.println("PracticeParent default constructor");
}
}
package com.moreTest;
import com.test.PracticeParent;
public class Test extends PracticeParent { //No Error
public static void main(String[] args) {
PracticeParent pp=new PracticeParent(); //Error. The constructor PracticeParent() is not visible
/*Test t=new Test(); outputs "PracticeParent default constructor"*/
}
}
Why is it that the super() is called but it is not possible to create a new PracticeParent object?