• Post Reply Bookmark Topic Watch Topic
  • New Topic

accessing private variable and private constructor using static method  RSS feed

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this code, I can create a new object of StaticTest class using static method getTStaticTest(). But I can not access static int i, using static method getI(). Does it mean that all constructors are implicitly static ? and thats why we can access private constructor but not non-static private variable ?

Thanks
 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
variable i is an instance level variable of class. this variable can be accessed only from object level method if you want to use it without prefixing it with any object reference.
Non static private variable are only accessible in object level context/methods.
Static method exist at class level .. so they do not allow usage of any instance variable directly (without attaching object reference to it).


Object creation is not dependent on static context/access restriction. You can create object in an static method.
Constructor are never static. Constructors are used for object creation.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!