4 Type of Java Access Modifiers Explained with Examples – MPS


This tutorial describes Java access modifiers in detail. They control the visibility for Java classes and their members (functions and data). They are public, private, and protected.

However, Java also implements a default case when no modifier is present. It means that a class, its functions, fields are only accessible by other classes in the same module.

By the way, there are majorly four types of access modifiers in Java. Let’s discuss each of them in detail and with the help of examples.

Java Access Modifiers Explained with Examples

The following are the points that we’ll discuss today.

Java Access Modifiers

Modifiers introduction

Java provides a wide variety of mechanisms to control the visibility of objects of a class or variable. They are known as modifiers in programming terminology.

They may belong to one of the following categories:

  • Access modifiers
  • Non-Access modifiers

Moreover, Java supports four primary access modifiers. While Non-access specifiers are of 7 types in Java. You can use them to specify the level of access to classes, methods, constructors, or variables.

The four primary access specifiers in Java are:

  • Default access modifier,
  • Private access modifier,
  • Public access modifier,
  • Protected access modifier,

As per the Java inheritance concept:

  • The public methods of a superclass must also have the same level in the subclass too.
  • Private methods wouldn’t be available to child classes.
  • Protected methods in the superclass are either public or protected in a subclass.

Default access modifiers

The default access modifier is accessible to any package by default. The programmers need not specify any keyword to use the default access modifier.

It means that the programmer doesn’t need to specify a class, method, or constructor default explicitly.

A class or method is, by default, accessible from any other “class” that exists in the same package. We usually don’t define variables and methods with any access modifier.

The example below shows a default class:

class Def 
   int num = 175;  
       void print() 
          System.out.println("Default class " + num); 
      
   

public class Test 
   public static void main(String args[]) 
      Def def = new Def();
      def.print();
   

As you would expect, the output is:

Default class 175

Private access modifiers

As the name suggests, the private access modifier limits access to the defining “class” only. With the help of the “private” keyword, we can implement the real concept of Data Encapsulation. It means to hide the private members form the outside world.

Also, please note that all user-defined variables, constructors, or methods can also have private access. Check out the following points:

  • The functions labeled as private are accessible within the class only.
  • You can’t declare a top-level class or interface as private. Also, if so, then it would be useless as no one could access it.
  • The programmer must define a getter or setter to access private methods or variables.

The example below will help you visualize a getter for the private method:

class Priv 
   private void PRINT() 
      System.out.println("Private access"); 
   

   public void getPrint() 
      PRINT();
   


public class Test 
   public static void main(String args[]) 
      Privpriv = new Priv();
      priv.PRINT();
   

In the example above, the getPrint() is a getter function for the private function PRINT(). The output is:

Private access

Public access modifiers

The public modifiers are the most common in Java applications. They mean that any public class, method, variable, interface, or constructor is accessible throughout the package.

  • Before using a public class in another package, you must first import it.
  • If you inherit a public class, then the subclass will have all its methods and variables by default.

For your info, the “main()” method in Java is public.

public class First {
   public void print() 
      System.out.println("Hello");
   

   public class Test extends First 
   public static void main(String args[]) 
      First first = new First();
      first.print();
   

The output is:

Hello

Protected access modifiers

Objects or methods having protected access are visible to the package and subclasses only.

The following are a few points to elaborate on the exact behavior:

  • These methods, variables, or constructors are accessible within the package only and also available to all the subclasses.
  • The protected keyword doesn’t apply to any class or interface.
  • Interface methods or variables can’t have protected access.

Look at an example below:

public class First 
   protected static int count;

   public void update()
      System.out.println(++count);
   

   public class Test extends First 

      public static void main(String args[]) 

         First out = new First();
         out.update();
      
   

The output is:

1

non-access modifiers

In Java programming, you will get seven non-access modifiers. You may prepend them with classes/methods/variables/constructors and use them in programs.

Here are some points to help you understand when should you use a particular modifier.

  • Static – It means something is directly related to a class.
  • Final – It indicates that the object is immutable.
  • Abstract – It means you need to subclass for creating objects.
  • Synchronized – It indicates that only one thread can execute a method at a time.
  • Transient – It means to exclude something during serialization.
  • Volatile – It indicates that different threads can modify a variable’s value.
  • Native – It shows that the method is available in the native code using JNI or JNA.

Key points

Here is a quick summary of the above concepts. It’ll help you make better use of access modifiers in Java.

  • If you are writing a class for reuse, then apply the most restrictive access level to those fields where it is logical.
  • Also, make the private access your default choice until there is a solid contrary case.
  • Moreover, don’t ever label constant identifiers as public.

We hope that reading this tutorial would have added a bit to your knowledge stack. If you wish to learn more, then please refer to the below post for the next steps.

Java Recommended  Post

Source link

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories

You have successfully subscribed to myprogrammingschool

There was an error while trying to send your request. Please try again.

My Programming School will use the information you provide on this form to be in touch with you and to provide updates and marketing.