Thinking in Java 4th edition - help with inner class exercise
Trying to solve this exercise: (Chapter Innerclasses, Exercise 6,
page 353)
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.
The following solution compiles and runs, but I had to use a public
method to instantiate the protected class in the 2nd package. Is
there a solution using the protected class directly? Shouldn't a
child class have access to protected members, including inner class
members, of parent class from another package.
_____________________________
/* // in first package:
* public interface Ex6Interface {
* String say();
* }
*
* // and in second package:
* public class Ex6Base {
* protected class Ex6BaseInner implements Ex6Interface {
* public String say() { return "Hi"; }
* }
* public Ex6BaseInner getEx6BaseInner() {
* return new Ex6BaseInner();
* }
* }
*/
// in third package:
import innerclasses.ex6Interface.*;
import innerclasses.ex6Base.*;
public class Ex6 extends Ex6Base {
private Ex6Base e6b;
Ex6() {
super();
e6b = new Ex6Base();
}
Ex6Interface getBaseInner() {
// Error: Ex6BaseInner has protected access:
// return e6b.new Ex6BaseInner();
// to create protected class use public method:
return e6b.getEx6BaseInner();
}
public static void main(String[] args) {
Ex6 ex = new Ex6();
// Error: Ex6BaseInner has protected access:
// Ex6Base.Ex6BaseInner ebi = ex.new Ex6BaseInner();
// new Ex6Base().new Ex6BaseInner();
System.out.println(ex.getBaseInner().say());
}
}
______________________________
thanks,
Greg