Java Public Private Protected Access Modifiers

Access modifiers of Java, are public, private, and protected. Java also defines a default access level. The protected modifier in Java, applies only when inheritance is involved. Let's take a look of these access modifiers available in Java language

Java Default Access Modifier

The access modifier will be default, in case if you doesn't explicitly declare an access modifier for a method, class, or field, etc.

Java public Access Modifier

When you declare a class, method, interface, or constructor, etc as public, then they can be accessed from anywhere, from any other class in the program. In case, if you try to access the public class (present in other/different package), then you have to import that public class.

Java private Access Modifier

When you declare a class, method, interface, constructor, or variable, as private can only be accessed within the class where they are declared. This is the most restrictive access level in Java.

Note - In Java programming, class and interface can't be private

Java protected Access Modifier

When you declare a variable, method, constructor as protected in a superclass, can only be accessed by the subclasses in the other package or any other class within the package of protected member's class.

Java Access Modifier Example

Here is an example program, illustrates the concept and use of access modifier in Java language:

/* Java Program Example - Java Access Modifiers
*  A simple example program of Java's access modifiers */

class MyTestClass
{
   int a;
    public int b;
    private int c;
    
    void setc(int temp) 
    {
        c = temp;
    }
    int getc() 
    {
        return c;
    }
}

public class JavaProgram
{   
    public static void main(String args[])
    {
        MyTestClass objct = new MyTestClass();
        objct.a = 100;
        objct.b = 200;
        System.out.println("a is " + objct.a + "\nb is " + objct.b + "\nc is " + objct.getc());
    }
}

When the above Java program is compile and executed, it will produce the following output:

java access modifiers

As you can see in above example, inside the class MyTestClass, a uses default access, which for this example is the same as specifying as public, b is explicitly specified as public. Member c is given private access. This means that it can't be accessed by the code that is outside of its class. So, inside the class JavaProgram, c can't be used directly. It must be accessed through its setc() and getc() public methods.

Java Online Test


« Previous Tutorial Next Tutorial »