user-avatar
Today is Thursday
February 23, 2012

March 22, 2011

What are the default and protected access modifiers?

by admin — Categories: CertificationComments Off

The default and protected access modifiers are identical modifiers with only one difference.

default: A default method or member can be accessed only by the class member that belongs to the same package. For example:

package book;
public class Outerclass
 {
   void test() //default access
     {
       System.out.println(“Outer Class”);
     }
 }

package book1;
import book.*;
class Innerclass
 {
   static public void main(String args[])
     {
       Outerclass oc= new Outerclass();
       oc.test(); // compilation error!
     }
 }

In the above example, there are two packages, book and book1. The package book has a class Outerclass and a method test, which has a default access level. The package book1 has a class Innerclass in which it declares an object of Outerclass. However, when it uses the test() method of the Outerclass, which has a default access level, it will generate a compile-time error No method matching test() found in class.

protected: If the protected modifier is used to define a member, any subclass of the class and its member can access the member through inheritance even if the subclass is in a different package. For example:

package book;
public class read
 {
   protected int r1=10;
 }

package book1;
import book.read;

class Doread extends read
 {
   public void test()
     {
       System.out.println(“The value of r1 is:” +r1);
     }
   }

In the above example, there are two packages, book and book1. The package book has a class read and a protected variable r1. The package book1 has a class Doread, which extends the class read. The compiler will easily access the variable r1 because it inherits the class read.
Click here to download GSSP-Java test study guide and practice question.
Download questions and guide CX310-019 for exam.

Share
© 2012 SCJP 4 You All rights reserved - Wallow theme v0.46.4 by ([][]) TwoBeers - Powered by WordPress - Have fun!