• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Confusion on access modifiers

 
Greenhorn
Posts: 8
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Guys,
Need your help here. I am trying to understand why the following code is compiling and running when it should fail compilation.


What i have understand from the theory is, subclasses outside the package can't use a superclass reference to access a protected member then why my code is working here with the static decleration.
If i remove the static keword it fails compilation which is accepted. I am trying hard to understand why it is compiling when i am using the static with the variable decleration. Please help me here.

[Edit - added code tags - see UseCodeTags for details]
 
Ranch Hand
Posts: 451
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If the x is non-static, child class can only inherit it and use as if x is defined in its own class.
If the x is static, it is a variable that belongs to the class, not belong to any object instance. You can use it by Parent.x or obj.x.
If you are running it in Eclipse, by using obj.x, you will get a warning that static variable should be called in a static way, Parent.x

By the way, if you do this:


Polymorphism does not apply to static variable or methods. c is a parent type. c.x refers to the x in Parent.
 
Amit K K Amit
Greenhorn
Posts: 8
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Helen,
Thanks for helping me understand the concept.
 
I’m tired of walking, and will rest for a minute and grow some wheels. This is the promise of this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic