Write a Java program to Create members with access modifier


The Create_Members class contains a main method which creates an object of the Demo class and calls its printValues method. The program also attempts to access the instance variables num1 and num2 of the Demo class using the dot notation. Unlike the previous example, the instance variables are not declared as private, so they can be accessed outside the class in which they are declared. Therefore, the program prints the values of num1 and num2 to the console using System.out.println.

The Demo class contains two instance variables, num1 and num2, which are initialized to 10 and 20, respectively. The printValues method prints the values of the num1 and num2 variables to the console using System.out.println. It also assigns new values to these variables, setting num1 to 30 and num2 to 40.

Therefore, when this program is executed, it demonstrates that instance variables declared without the private keyword can 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 instance variables to the console. The program then prints the values of the num1 and num2 instance variables using System.out.println. Finally, the printValues method is called again, which updates the values of num1 and num2 and prints the new values to the console.

Source Code

public class Create_Members
{
	public static void main(String[] args)
	{
		Demo d = new Demo();
		d.printValues();
 
		// accessed outside the class.
		System.out.println("Number 1 : "+d.num1);
		System.out.println("Number 2 : "+d.num2);
	}
}
class Demo
{
	int num1 = 10;
	int num2 = 20;
 
	void printValues()
	{
		System.out.println("Number 1 : "+num1);
		System.out.println("Number 2 : "+num2);
 
		num1 = 30;
		num2 = 40;
	}
}

Output

Number 1 : 10
Number 2 : 20
Number 1 : 30
Number 2 : 40