Q:

Java program to create members with private access modifier

belongs to collection: Java Class and Object Programs

0

Java program to create members with private access modifier

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

Program/Source Code:

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 num1num2. 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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to create members with access modifie... >>
<< Java program to read and add two distances using c...