aspose file tools*
The moose likes Beginning Java and the fly likes Inner Classes - Why can't i access a protected inner class' constructor in a subclass? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inner Classes - Why can Watch "Inner Classes - Why can New topic
Author

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

Suresh S Nayar
Greenhorn

Joined: Apr 25, 2009
Posts: 9
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

Joined: Jan 01, 2009
Posts: 874


Suresh,

Did you compile having classes in the same package ? check that.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Inner Classes - Why can't i access a protected inner class' constructor in a subclass?