Site icon TestingDocs.com

Java Access Modifiers

Introduction

In this post, we will discuss different Java access modifiers. Access modifiers set the access level of classes, variables, methods and constructors, etc in Java language. Access modifiers specify who can access them. Different types of access modifiers in Java are as follows:

default

default access modifier makes a member accessible only to the classes in the same package. Also,methods and variables of a class are collectively known as members of the class.default access modifier is when we don’t specify any modifier.

Sample examples:

class AccessModifiers {
  int a ;
  static int b;
  
  double calculateAverage()
  {
    return (a+b)/2 ;
  }

}

 

private

When we declare a variable or method with private access modifier,as a result the member would be accessible only from within its own class. Therefore, it is the most restrictive access level we can set in Java.

Example:

variables a , b and the method are declared with this modifier in the class.

public class AccessModifiers {
  private int a ;
  private static int b;
  
  private double calculateAverage()
  {
    return (a+b)/2 ;
  }

}

 

Note that we cant specify a class as private . We will get an error message as follows when we try to do so:

Illegal modifier for the class AccessModifiers; only public, abstract & final are permitted

public

When we declare with this access modifier all other classes regardless of the package that they belong to, can access them. Therefore, a class, method, constructor, interface etc declared with this modifier can be accessed from any other class.

Example

public class AccessModifiers {
  public int a ;
  public static int b;
  
  public double calculateAverage()
  {
    return (a+b)/2 ;
  }

}

 

 

protected

This access modifier would allow access only to classes in the same package or subclass of the class. Also, members like variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other packages or any class within the package of the protected member class.

public class AccessModifiers {
  protected int a ;
  protected  static int b;
  
  protected double calculateAverage()
  {
    return (a+b)/2 ;
  }

}

 

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version