Write a Java program to Create members with private access modifier


The Member_Private class contains a main method which creates an object of the Demo class and calls its printValues method. The program attempts to access the private instance variables num1 and num2 of the Demo class using the dot notation, but this results in a compilation error since private members cannot be accessed outside the class in which they are declared. Instead, the program calls the printValues method of the Demo object, which prints the values of the private instance variables num1 and num2 to the console using System.out.println.

The Demo class contains two private instance variables, num1 and num2, which are initialized to 12 and 20, respectively. The printValues method prints the values of the num1 and num2 variables to the console using System.out.println.

Therefore, when this program is executed, it demonstrates that private instance variables cannot be accessed outside the class in which they are declared. The program creates an object of the Demo class and calls its printValues method to print the values of its private instance variables to the console.

Source Code

public class Member_Private
{
	public static void main(String[] args)
	{
		Demo d = new Demo();
 
		//statement will generate an error We cannot access private member outside the class.
		//System.out.println("Number 1 : "+d.num1);
		//System.out.println("Number 2 : "+d.num2);
		d.printValues();
	}
}
class Demo
{
	private int num1 = 12;
	private int num2 = 20;
 
	void printValues()
	{
		System.out.println("Number 1 : "+num1);
		System.out.println("Number 2 : "+num2);
	}
}
 

Output

Number 1 : 12
Number 2 : 20