×

Java Programs

Java Practice

Java program to create members with private access modifier

Demonstrate the example of creating members with private access modifier in Java.
Submitted by Nidhi, on March 16, 2022

Problem statement

In this program, we will create two private members in a class and access them by a method outside the class.

Java program to create members with private access modifier

The source code to create members with a "private" access modifier is given below. The given program is compiled and executed successfully.

// 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

Explanation

In the above program, we created two classes Demo and Main. The Demo class contains two private members num1, num2. And, printed the value of private members using the printValues() method to access them outside the class.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created the object of the Demo class and called the printValues() method to access values of private members and printed them.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.