Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access violation with a protected

 
Leandro Oliveira
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

According to the rule of the default constructor, Outer.Inner has a protected constructor like the following:
protected Inner(){super();}
but why there is an error if this constructor is accessed in a sub class of Inner???
thanks in advance!!!
 
Anshul Chhabra
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The class Inner does not have a constructor defined at all. Therefore, Java will provide a default constructor for Inner.
According to JLS - the modifier for the constructor will be the same as the modifier for the class (in this case protected).
Therefore the declaration of Inner is effectively:
protected class Inner{
protected Inner(){}
}

With this in mind it is pretty clear why SonOfOuter cannot access Inner, since the constructor of Inner is now protected.
To check, try defining a public constructor within Inner and see if your code compiles now.
 
Dan Culache
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The piece of code is from the Java Language Specification and the explanation is there 8.8.7 Default Constructor
The constructor for Inner is protected. However, the constructor is protected relative to Inner, while Inner is protected relative to Outer. So, Inner is accessible in SonOfOuter, since it is a subclass of Outer. Inner's constructor is not accessible in SonOfOuter, because the class SonOfOuter is not a subclass of Inner! Hence, even though Inner is accessible, its default constructor is not.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic