Reading through "Thinking in Java" i stuck in ex:6 of Inner Classes chapter.
Exercise 6: (2) Create an interface with at least one method, in its own package. Create a class in a separate package. Add a protected inner class that implements the interface. In a third package, inherit from your class and, inside a method, return an object of the protected inner class, upcasting to the interface during the return.
This is my code:
interface
package intfpack;
public interface IOne{
void f();
}
Class with protected inner class that implements the interface
package classpack;
import intfpack.*;
public class COne{
protected class Inner implements IOne{
public void f(){System.out.println("Inner class of COne");}
}
}
Inheriting from class with protected inner class
package thirdpack;
import classpack.*;
import intfpack.*;
public class CTwo extends COne{
public IOne getInner(){
IOne io = new Inner();
return io;
}
public static void main(String[] args){
CTwo ct = new CTwo();
ct.getInner();
}
}
Copmiler says next:
javac CTwo.java
CTwo.java:9: Inner() has protected access in classpack.COne.Inner
IOne io = new Inner();
^
1 error
But the book says that i can access protected inner classes in derived class. Where is mistake?
In order to access your demo12 inner class from demo2 class, demo2 class has to extend demo1 . More over, inner classes are connected with instances of the class, so you can not call it directly from the static method. Check the difference between inner and nested classes. Show activity on this post.
Inner classesA inner class declared in the same outer class (or in its descendant) can inherit another inner class.
The protected access modifier is accessible within the package. However, it can also accessible outside the package but through inheritance only. We can't assign protected to outer class and interface. If you make any constructor protected, you cannot create the instance of that class from outside the package.
Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access.
The error message is complaining about the constructor being protected, not the class. But you haven't explicitly defined a constructor in the code you posted. In this case, according to the JLS, the default constructor will be protected (the same as the class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With