Sunday 3 April 2016

java - Why can't I use protected constructors outside the package?




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
}
}



  1. Why do i get the error even though i have extended the class?
    Please explain




EDIT:



Compilation error:




The constructor Example() is not visible



Answer



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.



package Super;

public class SuperConstructorCall {

protected SuperConstructorCall() {
}


}

package Child;

import Super.SuperConstructorCall;

public class ChildCall extends SuperConstructorCall
{

public static void main(String[] args) {


SuperConstructorCall s = new SuperConstructorCall(); // Compile time error saying SuperConstructorCall() has protected access in SuperConstructorCall
}
}


Example 2 conforming to JLS 6.6.2.2:



package Super;


public class SuperConstructorCall {

protected SuperConstructorCall() {
}

}

package Child;

import Super.SuperConstructorCall;


public class ChildCall extends SuperConstructorCall
{

public static void main(String[] args) {

SuperConstructorCall s = new SuperConstructorCall(){}; // This will work as the access is by an anonymous class instance creation expression
}
}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...