• 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
  • Bear Bibeault
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Frits Walraven
Bartenders:
  • Carey Brown
  • salvin francis
  • Claude Moore

a simple question  RSS feed

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


can't the var "x" in class Test2 be seen ?

why is here no errors ?
 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're calling the public function print, that's why it's fine. You cannot directly access x's value.
 
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It can be seen but not directly referenced.For example, you couldn't say:



..neither could you call it statically, unless it was a class variable (static)



In your case as you are calling the method in the first occasion on an instance of the Test1 class and the method is public than the method works fine.

In the second method you are calling the print method inherited by the Test2 class which again because its public in the parent class its visible.

Visibility in this case,limits the direct reference of a member variable ie,to x. However the public access modifier on the print method means the print method is visible and works, AND ensures a degree of encapsulation (accessing x only through a public interface). Thus your examples are the same as the getter and setters conventions (accessor and mutators)

Steve
[ October 03, 2008: Message edited by: Stephen Davies ]
 
You ridiculous clown, did you think you could get away with it? This is my favorite tiny ad!
Create Edit Print & Convert PDF Using Free API with Java
https://coderanch.com/wiki/703735/Create-Convert-PDF-Free-Spire
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!