Friday, October 9, 2009

Access Modifiers in Java


I've always felt that the standard explanation for Access Modifiers in Java:
  • Public = Accessible to All
  • Protected = Accessible to the Class, any Class in the same Package, and any Subclass
  • Default = Accessible to the Class, and any Class in the same Package
  • Private = Accessible only to the Class itself. 
...wasn't entirely accurate (and admittedly, since most designs stick with basic encapsulation: private fields and public methods, more specific details are often academic).

So to illustrate the complexity, I've created three simple classes.  The first two, "Parent" and "Child" are in the same package.


package com.intertech.examples.java.accessmodifiers;

public class Parent
{
   public void printPublicMessage()
   {
      System.out.println( "printPublicMessage()" );
   }

   protected void printProtectedMessage()
   {
      System.out.println( "printProtectedMessage()" );
   }

   void printPackageMessage()
   {
      System.out.println( "printPackageMessage()" );
   }

   private void printPrivateMessage()
   {
      System.out.println( "printPrivateMessage()" );
   }
}


and ...


package com.intertech.examples.java.accessmodifiers;

public class Child extends Parent
{
   // Does nothing but extend Parent
}


Which methods from "Parent" do you think would be visible to the three objects below (note that this class extends Parent as well, but is in another package). 

package com.intertech.examples.java.accessmodifiers.another;

import com.intertech.examples.java.accessmodifiers.Child;
import com.intertech.examples.java.accessmodifiers.Parent;

public class AnotherChild extends Parent
{
   public static void main( String[] args )
   {
      Parent parent = new Parent();
      /* which "Print" methods from the Parent class would be visible for this Parent object? */

      Child child = new Child();
      /* which "Print" methods from the Parent class would be visible for this Child object? */

      AnotherChild anotherChild = new AnotherChild();
      /* which "Print" methods from the Parent class would be visible for this AnotherChild object? */
   }
}

Try to do this without putting it into an IDE or running the actual code. I'll post the answers next week with some further explanation.  You can find more information on "Complete Java" or other courses taught at Intertech - by visiting our website: http://www.intertech.com/

0 comments:

Post a Comment