Java Program to Create Members With Private Access Modifier

You are currently viewing Java Program to Create Members With Private Access Modifier

Java program to create members with private access modifier

// Java program to create members with 
// "private" access modifier

class Demo {
  private int num1 = 10;
  private int num2 = 20;

  void printValues() {
    System.out.printf("Num1: %d\n", num1);
    System.out.printf("Num2: %d\n", num2);
  }
}
public class Main {
  public static void main(String[] args) {
    Demo d = new Demo();

    //Below statement will generate an error
    //We cannot access private member outside the class.
    //System.out.printf("Num1: %d\n", d.num1);

    d.printValues();
  }
}

Output

Num1: 10
Num2: 20

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply