Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inner Classes - Why can't i access a protected inner class' constructor in a subclass?

 
Suresh S Nayar
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't i access a protected inner class' constructor in a subclass?

Assume,

//Inteface1.java
package packagea;

public interface Interface1{
void f();
}

//Class1.java
package packagea;
public class Class1{
protected class InnerClass implements Interface1{
public void f(){
System.out.println("Class1.InnerClass.f()");
}
}
}

//SubClass.java
package packageb;
import packagea.*;
public class SubClass extends Class1{
public Interface1 getInterface1(){
return new InnerClass(); //Error thrown here in JDK
}

public static void main(String [] args){
new SubClass().getInterface1().f();
}
}
Error Message in JDK1.5.0.12: "InnerClass() has protected access in packagea.Class1.InnerClass"

I dont understand why this error is thrown? As a subclass, i have the rights to access protected members of a

superclass, innit? Or are the rules different for constructors of inner classes?

As expected, all the files compile and the app runs if i make a public default constructor for InnerClass.
 
Balu Sadhasivam
Ranch Hand
Posts: 874
Android Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Suresh,

Did you compile having classes in the same package ? check that.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html, section 8.8.7:
The rule that the default constructor of a class has the same access modifier as the class itself is simple and intuitive. Note, however, that this does not imply that the constructor is accessible whenever the class is accessible.

The automatically generated constructor of the inner class is protected, which means that only classes in packagea and subclasses of that inner class can access it. Although SubClass does inherit the class itself, it is neither in packagea nor is it a subclass of the inner class. That's why you can't access the constructor.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic