PhysicsTeacher.in

High School Physics

Java program – how to access private variable

This Java program shows how to access a private variable. This will help you to understand the use of access specifiers.

Access specifier in Java program | Accessing private variable using Java

class AccessTest
{
int i; //default access
public int j;
private int k;

/*accessing private variable through a method*/

void setVal (int p)
{

k=p;
}

void writeVal()
{
System.out.println(“value of i=”+i);
System.out.println(“value of j=”+j);
System.out.println(“value of k=”+k);

}

}

class TestMain

{
public static void main(String args[])
{
AccessTest test=new AccessTest();
test.i=10;
test.j=12;

/* next commented line (in red) won’t compile. (error shown: k has private access in AccessTest) */

//test.k=14;
test.writeVal();
test.setVal(14);
test.writeVal();
}

}

output of the Java program


value of i=10
value of j=12
value of k=0
value of i=10
value of j=12
value of k=14

See also  Java program - how to use the Scanner class to capture user input
Scroll to top
error: physicsTeacher.in