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

// 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();
  }
}
Num1: 10
Num2: 20

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

Share on:

Leave a Comment