Demonstrate Private access modifier in Java


The data members and methods of a class can be accessed only from within their declared class if they are specified with the private access modifier. The keyword private is used to specify this modifier.

A program that demonstrates the private access modifier in Java is given as follows:

Example

 Live Demo

class A {
   private int a = 6;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}
public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.printA();
   }
}

Output

Value of a = 6

Now let us understand the above program.

The class A has a private data member a that can be accessed only from within the class. The method printA() displays the value of a. A code snippet which demonstrates this is as follows:

class A {
   private int a = 6;
   public void printA() {
      System.out.println("Value of a = " + a);
   }
}

In the main() method in class Demo, an object obj of class A is created. Then printA() method is called. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String args[]) {
      A obj = new A();
      obj.printA();
   }
}

Updated on: 30-Jul-2019

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements