Thinking in Java Fourth Edition Bruce Eckel Chapter 5 Exercise 4

Exercise 4: Show that protected methods have package access but are not public.

package access.cookie2;

public class Cookie
{
    public Cookie()
    {
        System.out.println("Cookie contstructor");
    }
    protected void bite()
    {
        System.out.println("bite");
    }
}
package access.cookie2;

public class CookieMonster
{
    public static void main(String[] args)
    {
        Cookie x = new Cookie();
        x.bite(); // package access to protected method
    }  
}
import access.cookie2.*;

public class CookieThief
{
    public static void main(String[] args)
    {
        Cookie x = new Cookie();
        //! x.bite(); // access protected
    }  
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *