well.... actually your "class PrivateClass" isn't really private. It's of the default protection level (sometimes called "package"). The default modifier gives access to all classes in the same package. So, your MainClass has access to PrivateClass. And also, any other class you add to this package, will have access to PrivateClass. Does that help? Can you write some code for a class that doesn't have access to PrivateClass?
Hi Jess, Yes...that is what I was thinking... I guess my question is - Is there anyway to access public methods of a class which has been declared private ? It's not something that I want to do, it's just something that I want to know. Thanks..
Is there anyway to access public methods of a class which has been declared private ? Yes. Well, obviously you can access those methods from within the same class. But I'm guessing you mean, is there a way to access the public methods from outside the private class - and the answer is yes. However this requires that the private class extend a public class, or implement a public interface, which declares the methods in question.
Here class C is private, which means that D can't call it directly. But B can, and B is allowed to return a reference to C, and pass it to D. D does not know much about what B really is, but D does know that B is an A, and has a foo() method, so D is allowed to call that method. This technique may seem a bit convoluted or arbitrary here, as the classes invovled don't have any apparent purpose. But this technique is used reasonably often in actual programming, to provide an implementation of a public interface without expsong details about the particular implementation used. For simplicity I've just discussed public vs. private here. We could also apply the same discussion to public vs. protected, private vs. package, package vs. public, package vs. protected, or protected vs. public - the basic idea is the same for any method with higher access level than the class which contains it. Of course if we're implementing an interface, the interface methods are necessarily public - but protected and package are relevant if we're extending a class rather than implementing an interface.