There are there types of access modifiers in Java.
They are: public private and protected.
public: A public data can be accessed by outside of the code in which it is
private: A private data can not be accessed by outside of the code in which it is defined. The private data can be accessed by
protected: A protected access control is similar to the private only difference is that it has a access to their derived classes. Protected applies only when inheritance outside.
Difference between public and private
class Demo {
int a;//default variable can access in same package
public int b;
private int c;
void setc(int i) {
c = i;
}
int getc() {
return c;
}
}
public class Test {
public static void main(String arg[]) {
Demo obj = new Demo();
obj.a = 10;//ok
obj.b = 20;//ok
obj.c = 30;// error, c can’t be accessed here
obj.setc(30);// ok
System.out.println("a =" + obj.a + " b=" + obj.b + " c=" + obj.getc()
);
}
}
Result
If you comment line obj.c = 30;// error, c can’t be accessed here. then following result will produce
a =10 b=20 c=30
Private data can not be directly accessible outside class