Practical use of protected in Java


  • 1

    It is quite hard to come by practical use cases of protected by doing a Google search! There are countless examples of usage but these examples exist for mere syntax clarification. So when would we really want ONLY a subclass to access a certain method (by inheritance) ?

    Here is a practical use case:

    Consider the following protected method which belongs to AbstractList

    protected void removeRange(int fromIndex, int toIndex)
    

    This method provides a default (very inefficient) way to remove a series of elements within a list and which is internally invoked by the public clear method. In the documentation for this method, it is advised that people override this method to hook in more efficient implementations.
    Thus, we have a situation where we have a method which represents internal functionality must be overriden. We want only subclassers to have access to this method and not any public client.

    Another example is HttpServlet from Java EE:

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    

    doGet is a method that is called by the web container when a GET request is sent against a particular URL. This clearly highlights that it is a callback. A callback is something that is never invoked explicitly by client code. The following will never arise in your application code:

    servlet.doGet(req, response);
    

    Thus there is no need to provide public access to it. The only access required is through inheritance, since we would have to override doGet to specify what happens when we receive this request.

    public class MyServlet extends HttpServlet {
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
    		//process request and send response
    	}
    }
    

    A similar example would be the protected finalize method in class Object, a callback which provides a chance to objects to run cleanup before being destroyed. The same reasoning applies.


Log in to reply
 

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