TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Java Access Modifiers
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java OOPJava Tutorials

Java Access Modifiers

Last updated: Apr 23, 2024 3:28 pm
By Meenakshi Agarwal
Share
8 Min Read
Java Access Modifiers
SHARE

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

Contents
Introduction to Java access modifiersDefault access modifiersPrivate access modifiersPublic access modifiersProtected access modifiersNon-access modifiersKey points

Understand Java Access Modifiers with Examples

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

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

Java Access Modifiers

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

Introduction to Java access modifiers

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.

As a matter of fact, they 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.

Firstly, we’ll cover the four primary access specifiers which are as follows:

  • Default access modifier
  • Private access modifier
  • Public access modifier
  • Private access modifier

As per the Java inheritance concept:

  • The public methods of a superclass must also have the same level in the subclass.
  • 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.

Given these points, here is an example illustrating the default class:

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

public class Main {
   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 from 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 in Java as private. And, even if you do, it would be useless as no one could access it.
  • The programmer must define a getter or setter to access private methods or variables.

Given these points, consider the below example to visualize the use of private access modifiers:

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

   public void getPrint() {
      System.out.println("getPrint(): Calling PRINT()");
      PRINT();
   }
}

public class Main {
   public static void main(String args[]) {
      Priv priv = new Priv();
      System.out.println("Private access");
      priv.PRINT();
      priv.getPrint();
   }
}

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

Test.java:16: error: PRINT() has private access in Priv

In order to fix the above error, comment the priv.PRINT(); line and then run the above program:

Private access
getPrint(): Calling PRINT()
PRINT(): 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.

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

public class Main 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:

class First {
   protected static int count;
   public void update(){
      System.out.println(++count);
   }
}

public class Main 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 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 has added a bit to your knowledge stack. If you wish to learn more, then please refer to the below post for the next steps.

What to Learn in Java to Crack an Interview?

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Top 10 Python Libraries for Data Science The Best 25 Python Libraries for Data Science
Next Article Java ArrayList Explained with Examples Java ArrayList with Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x