Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

When can a class access its own private members?

 
Ranch Hand
Posts: 209
13
VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose a test class contains a static inner class Dog, which it instantiates and makes bark.

Everything works, even if I instantiate a Dog in the over-complicated fashion of line 7.
Assuming that class can access its own private members, I was expecting this to work exactly the same if Dog is declared private, but that's not the case. The code compiles, but throws an IllegalAccessException.


So, is it not true to say, without qualification, that a class can access it's own private members?

 
Saloon Keeper
Posts: 12442
269
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're not asking the PrivateTest1 class to access Dog. You're asking Class to access it, and Dog is not a private member of Class.
 
Richard Hayward
Ranch Hand
Posts: 209
13
VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Stephan.

Stephan van Hulst wrote:You're asking Class to access it, and Dog is not a private member of Class.


Trying to think that through, Class is in java.lang, a different package from PrivateTest1 and I didn't declare the static nested class Dog as public, so from the perspective of java.lang.Class, even in my PrivateTest1 example, Dog shouldn't be visible.

This might involve a deeper enquiry into the workings of java.lang.Class than I need for practical purposes
 
Marshal
Posts: 70727
288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider introspection methods, including newInstance() as advanced topics not for everyday use.
 
Have you no shame? Have you no decency? Have you no tiny ad?
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic