1.

Default vs Protected access specifiers in Java

Answer»

The access specifiers in Java specify the scope of the data members, constructors, methods etc. of the class. Details about the DEFAULT and protected access specifiers are given as follows:

Default Access Specifier

The default access specifier is used when no access specifier is clearly provided by the PROGRAMMER. The data members, constructors, methods etc. that have the default access specifier are only accessible in the same package.

A program that demonstrates the default access specifier in Java is given as follows:

package pack1;   class C1 {      void print()    { System.out.println("This is in package p1");    } }  package pack2;   IMPORT pack1.*;   class C2 {     public static void main(String args[])   {   C1 obj = new C1();   obj.print();   } }  

Execution of the above program results in compile time error as the access specifier of class C1 and print() is default and so they cannot be accessed from outside the package pack1.

Protected Access Specifier

The protected access specifier can be used on the class data members or methods with the protected keyword. This MEANS that the data members are accessible INSIDE the package and in other packages using inheritance. The protected access specifier cannot be directly applied on a class but it can be applied on a data member, constructor or method.

A program that demonstrates the protected access specifier in Java is given as follows:

package pack1;   public class C1 {      protected void print()    { System.out.println("This is in package p1");    } }  

Another package:

package pack2;   import pack1.*;   class C2 extends C1 {     public static void main(String args[])   {   C1 obj = new C1();   obj.print();   } }

The output of the above program is as follows:

This is in package p1


Discussion

No Comment Found