Java inner class and inheritance

I am currently reading Thinking in Java, and I ran into one small problem. I am doing exercise 12 of chapter 8.

Create an interface with at least one method in your own package. Create the class in a separate package. Add a secure inner class that implements the interface. In the third> package, inherit from your class and inside the method return an object of the protected> inner class, which increases the level of display in the interface during the return.

So, I created these .java files:

A.java

package c08; public interface A { void one(); } 

Pr2.java

  package c082; import c08.*; public class Pr2 { protected class InPr2 implements A { public void one() {System.out.println("Pr2.InPr2.one");} protected InPr2() {} } } 

Ex.java

  package c083; import c082.*; import c08.*; class Cl extends Pr2 { A foo() { InPr2 bar=new InPr2(); return bar; } } 

And my NetBeans IDE emphasizes

  InPr2(); 

and says that: InPr2 () has secure access in C082.Pr2.InPr2, and I wonder why. If I didn’t explicitly indicate that the InPr2 constructor should be protected, it will be available only in the C082 package, but when I inherit the Pr2 shoudn't class, will it be available in the Cl class because InPr2 is protected? Everything is fine when I change the constructor to public.

+7
source share
6 answers

It should work very well, just like you, except changing protected InPr2() {} to public InPr2() { } . In other words: "Anyone can instantiate this class IF they can see the class to begin with."

+2
source

The InPr2 constructor is protected, which means that only classes that inherit from InPr2 (not Pr2 ) can call it. Classes that inherit from Pr2 can see the Pr2 class, but they cannot invoke its protected members, such as the protected constructor.

+4
source

Even if the InPr2 class is available in Cl , its constructor is not . The protected constructor is available only for subclasses and classes in one package.

+1
source

Edit:

Pr2.java

 package c082; import c08.*; public class Pr2 { protected class InPr2 implements A { public void one() {System.out.println("Pr2.InPr2.one");} // This constructor was available only // to a class inheriting form Pr2.InPr2 - protected InPr2() {} public InPr2() {} } } 

The constructor from Pr2.InPr2 was only accessible to the class if it extended Pr2.InPr2 .

0
source

Protected member variables, methods, and constructors are not available outside the package if they are not inherited. When we try to create an InPr2 object, the compiler will show an error, since the protected constructor is not available outside the package. Creating an object also depends on the constructor access modifier.

You can do one thing: InPr2 can be inherited inside class C.

0
source

java class cannot be protected.

-one
source

All Articles