• Post Reply Bookmark Topic Watch Topic
  • New Topic

access modifiers and constructor  RSS feed

 
Jack McLaren
Greenhorn
Posts: 13
Mac Mac OS X Mac PPC
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I have following two questions :

Why code at //1 is valid ? JVM will provide constructor for Parent class, that is not package private ? if not then what is access modifier of that constructor ?

Why code at //2 is invalid although parentMethod() is protected but Child extends Parent class so it should work ?
 
Paweł Baczyński
Bartender
Posts: 2074
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jack McLaren wrote:
Why code at //1 is valid ? JVM will provide constructor for Parent class, that is not package private ? if not then what is access modifier of that constructor ?

It is protected. So any class in the same package AND any child of that class (or child of a child and so on...) might access it.

Jack McLaren wrote:
Why code at //2 is invalid although parentMethod() is protected but Child extends Parent class so it should work ?

Because my above statement only applies to inheritance (extending a class) and seeing a class as a whole (and that includes any protected constructors), but not accessing other class' fields or methods.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pawel Pawlowicz wrote:
Jack McLaren wrote:
Why code at //1 is valid ? JVM will provide constructor for Parent class, that is not package private ? if not then what is access modifier of that constructor ?

It is protected. So any class in the same package AND any child of that class (or child of a child and so on...) might access it.

Not quite. The constructor the JVM makes is a public, no arguments constructor, and is only made if you do not provide one yourself.
 
Paweł Baczyński
Bartender
Posts: 2074
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Steve Luke wrote:
Pawel Pawlowicz wrote:
Jack McLaren wrote:
Why code at //1 is valid ? JVM will provide constructor for Parent class, that is not package private ? if not then what is access modifier of that constructor ?

It is protected. So any class in the same package AND any child of that class (or child of a child and so on...) might access it.

Not quite. The constructor the JVM makes is a public, no arguments constructor, and is only made if you do not provide one yourself.

You are right. I was reading the code too fast and I "saw" a protected constructor there ;). My bad.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!