• Post Reply Bookmark Topic Watch Topic
  • New Topic

Acccessing of Static members using null Reference.  RSS feed

 
Greenhorn
Posts: 20
Eclipse IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why static member are allowed to be accessed with class-name and a null reference?

Here's the given code.


In this code the static members of a class are accessible by the null reference of that class.
These can also be access by the class (Employee.companyId or Employee.getCompanyId()).

What is the difference here in both. why a null reference can access these static members.
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you access static variable the compiler treats emp.companyId as Employee.companyId so the fact that emp is null does not matter.
Although possible, it is not recommended to access static members of a class using reference variable.
 
Ranch Hand
Posts: 136
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static variables were designed to be common to all objects of a class. This fields has one fixed memory location. The static fields (also called class variables) are associated with the class, not with any specific object.

All the instance of the class shares the static variable which can be manipulated without creating an instance of the class.
 
Vimlesh Kumar Patel
Greenhorn
Posts: 20
Eclipse IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pawel Pawlowicz wrote:When you access static variable the compiler treats emp.companyId as Employee.companyId so the fact that emp is null does not matter.
Although possible, it is not recommended to access static members of a class using reference variable.


Thank you Pawel Pawlowicz.
 
Vimlesh Kumar Patel
Greenhorn
Posts: 20
Eclipse IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Balagopal Kannampallil wrote:Static variables were designed to be common to all objects of a class. This fields has one fixed memory location. The static fields (also called class variables) are associated with the class, not with any specific object.

All the instance of the class shares the static variable which can be manipulated without creating an instance of the class.


Thank you "Balagopal Kannampallil"
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!