What is the difference between public, protected, and private in Java and how do these rules differ when they are applied to a superclass?


  • 1
    U

    Public: A class, method, constructor, interface, etc. declared public can be accessed from any other class.

    Protected: Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

    Private: Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.

    Rules for superclass:

    1. Methods declared public in a superclass also must be public in all subclasses.
    2. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
    3. Methods declared private are not inherited at all, so there is no rule for them.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.