What are the differences between protected and default access specifiers in Java?

JavaObject Oriented ProgrammingProgramming

The Protected access specifier is visible within the same package and also visible in the subclass whereas the Default is a package level access specifier and it can be visible in the same package.

Protected Access Specifier

  • Protected will acts as public within the same package and acts as private outside the package.
  • Protected will also act as public outside the package only with respect to subclass objects.
  • Protected fields or methods cannot be used for classes and Interfaces.
  • The Fields, methods, and constructors declared as protected in a superclass can be accessed only by subclasses in other packages.
  • The classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member’s class.

Example

Live Demo

public class ProtectedTest {
   // variables that are protected
   protected int age = 30;
   protected String name = "Adithya";

   /**
    * This method is declared as protected.
    */
   protected String getInfo() {
      return name +" is "+ age +" years old.";
   }
   public static void main(String[] args) {
      System.out.println(new ProtectedTest().getInfo());
   }
}

Output

Adithya is 30 years old.


Default Access Specifier

  • Any member of a class mentioned without any access specifier then it is considered that as Default.
  • The Default will act as public within the same package and acts as private outside the package.
  • The Default members of any class can be available to anything within the same package and can not be available outside the package under any condition.
  • The Default restricts the access only to package level, even after extending the class having default data members we cannot able to access.

Example

Live Demo

public class DefaultTest {
   // variables that have no access modifier
   int age = 25;
   String name = "Jai";

   /**
    * This method is declared with default aacees specifier
    */
   String getInfo() {
      return name +" is "+ age +" years old.";
   }
   public static void main(String[] args) {
      System.out.println(new DefaultTest().getInfo());
   }
}

Output

Jai is 25 years old.
raja
Published on 25-Jun-2019 10:24:01
Advertisements