2

I have a question about public and private classes in Java. For example, if you have a public method inside of a private class, can the public method by accessed by other public/private classes? Thanks in advance.

3 Answers 3

2

In order to be able to invoke a method inside a class, the method that does the invocation must have access to the class itself. Therefore, methods of the class inside of which a private class is defined will have access to the public method, and methods of other classes would not have the access.

Of course if a private class inherits a public class or implements a public interface, the methods of the base class or the interface will be visible to everyone.

Sign up to request clarification or add additional context in comments.

Comments

1

Depends. If the public method is defined by a public interface, callers can access it through the interface. Otherwise, they would not be able to get a reference to it without using the private class (that they cannot see).

Also, with reflection and disabled security manager, you can do these things, too, but that is a different question, I guess.

Comments

-1

There can not be private class. Class can only have public or default access level.

1 Comment

Not true. Nested classes can be private.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.