File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes a simple question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a simple question" Watch "a simple question" New topic
Author

a simple question

zhu weitao
Greenhorn

Joined: Sep 02, 2008
Posts: 9


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

why is here no errors ?
Shashank Agarwal
Ranch Hand

Joined: May 20, 2004
Posts: 105
You're calling the public function print, that's why it's fine. You cannot directly access x's value.
Stephen Davies
Ranch Hand

Joined: Jul 23, 2008
Posts: 352
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 ]

be a well encapsulated person, don't expose your privates, unless you public void getWife()!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a simple question