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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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
1 | a =10 b=20 c=30 |
Private data can not be directly accessible outside class