Java/J2EE and SOA (325 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (324 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

Access Modifiers in Java: All you need to know

Last updated on Nov 27,2019 1.3K Views
54 / 72 Blog from Java Core Concepts

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Access modifiers in Java are used to specify the access levels for classes, variable methods, and constructor. It helps in updating the value of a variable. They are also known as visibility modifier. Through the medium of this blog, I will help you understand what is the importance of access modifiers in Java.

I’ll be covering the topics in the following order:

Let’s begin with the first topic.

What is Access Modifier?

You might’ve come across public, private and protected keywords while practicing any Java programs, these are called the Access Modifiers. As the name suggests, Access Modifiers in Java helps to restrict the scope of a class, constructor, variable, method or data member. 

Access modifiers can be specified separately for a class, constructors, fields, and methods. They are also referred as Java access specifiers, but the correct name is Java access modifiers.

So, let us dig deep into the different types of Access Modifiers in Java.

Types of Access Modifier

There are four access modifiers keywords in Java and they are:

  • Default Access Modifier
  • Private Access Modifier
  • Public Access Modifier
  • Protected Access Modifier

Let us learn about each one of them in detail.

Default Access Modifier

When no access modifier is specified for a particular class, method or a data member, it is said to be having the default access modifier. 

The date members, class or methods which are not declared utilizing any entrance modifiers, will have default modifier which is accessible only inside a similar bundle. It means you do not explicitly declare an access modifier for a class, field, method, etc.

Example:


package p1;

//Class Course is having Default access modifier

class Course{

void display()

{
System.out.println("Hello World!");

}

}

Next, let us move on to the next type, private access modifier.

Private Access Modifier 

  • The methods or data members that are declared as private are only accessible within the class in which they are declared.
  • Top level classes or interface cannot be declared as private in light of the fact that
    • Private signifies “just visible inside the enclosing class“.
    • Protected signifies “just noticeable inside the enclosing class and any subclasses“.
    • If a class has a private constructor then you cannot create the object of that class from outside the class.
    • Classes cannot be marked with the private access modifier.
    • Denoting a class with the private access modifier would imply that no different class could get to it. This generally implies that you cannot utilize the class by any stretch of the imagination. In this way, the private access modifier does not take into account classes.

        Note: Class or Interface cannot be declared as private. 

        Syntax:

        public class Clock {
            private long time = 0;
        }
        

        Take a look at an example to get a clear idea about this private access modifier.

        Example:

        package p;
        class A {
        private void display(){
        System.out.println("Edureka");
        }
        }
        class B {
        public static void main(String args[]){
        A obj = new A();
        //trying to access private method of another class
        obj.display();
        }
        }

        The output of this program is:

        error: display() has private access in A

        obj.display();

        Hope you guys are clear with private access modifier. Next, let’s move on to the next type, public access modifier.

        Public Access Modifier 

        • The public access modifier is specified using the keyword public. 
        • The public access modifier has a broad scope among all other access modifiers.
        • Classes, methods or data members which are declared as public are accessible anywhere throughout the program. There is no restriction on the scope of public data members.

        Syntax:

        package edureka.co;
        public class PublicClassDemo {
        // Here I didnt mention any modifier so it acts as a default modifier
        public int myMethod(int x){
        return x;
        }
        }

        Now, take a look at an example to get a clear idea about this public access modifier.

        Example:

        
        package p1;
        public class A
        {
        public void display()
        {
        System.out.println("edureka!");
        }
        }
        
        package p2;
        import p1.*;
        class B
        {
        public static void main(String args[])
        {
        A obj = new A;
        obj.display();
        }
        }
        

        Output: edureka!

        This is everything about public access modifiers in Java.

        Let’s move ahead to the next access modifiers in Java, protected access modifiers.

        Protected Access Modifier 

        • The protected access modifier is specified using the keyword protected.
        • The methods or data members declared as protected are accessible within the same package or subclasses in a different package.
        • Protected members can be accessed only in the child or derived classes.

        Syntax:

        package packageFourProtected;
        public class ProtectedClassFour
        {
        protected int myMethod(int a){
        return a;
        }
        }

        Let us take a look at an example.

        Example:

        spackage p1;
        //Class A
        public class A
        {
        protected void display()
        {
        System.out.println(" Java Certification Training");
        }
        }
        
        
        
        package p2;
        
        import p1.*; //importing all classes in package p1
        //Class B is subclass of A
        class B extends A |
        {
        public static void main(String args[])
        {
        B obj = new B();
        obj.display();
        }
        }
        

        Output - Access modifiers in Java - Edureka

        This is everything you need to know about the different methods under the access modifiers in Java. Let’s move ahead to the next topic.

        Access modifiers with method overriding

        If in case, you are overriding any method, the overridden method which is declared in the subclass must not be restrictive.

        Take a look at the below example.

        class A
        {
        protected void msg()
        {
        System.out.println("Hello java");
        }
        }
        public class Simple extends A { void msg()
        {
        System.out.println("Hello java");
        }
        //C.T.Error
        public static void main(String args[])
        {
        Simple obj=new Simple();
        obj.msg();
        }
        }

        The default modifier is more restrictive than protected. This is why there is a compile-time error.

        Access Control and Inheritance

        • If in case, you create a subclass of some class, then the methods in that subclass cannot have less accessible access modifiers assigned to them than the superclass.
        • For instance, if a method in the superclass is public then it must be public in the subclass too. If a method in the superclass is protected, then it must be either protected or public in the specified subclass.
        • Methods declared as private are not inherited at all.

        This brings us to the end of this article where we have learned the frequently asked questions on the Access modifiers in Java. Hope you are clear with all that has been shared with you in this tutorial.

        Make sure you practice as much as possible and revert your experience.  

        If you found this article on “Access Modifiers in Java” relevant, check out the Edureka Java Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

        If you come across any questions, feel free to ask all your questions in the comments section of “Access Modifiers in Java” and our team will be glad to answer.

        Comments
        0 Comments

        Browse Categories

        webinar REGISTER FOR FREE WEBINAR
        REGISTER NOW
        webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

        Subscribe to our Newsletter, and get personalized recommendations.