Java's access modifiers are public, private, and protected.
Java also defines a default access level. If we do not specify any access modifiers, Java uses default value access control.
protected
is applied for inheritance.
When a member of a class is modified by public, the member can be accessed by any other code.
When a member of a class is specified as private, the member can only be accessed by its class.
Here is an example:
public int i; private double j; private int myMethod(int a, char b) { //... }
Here is an example to illustrate the the effects of public and private access:
//demonstrates the difference between public and private. class Test {/*from w ww.ja va2 s.co m*/ int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) { // set c's value c = i; } int getc() { // get c's value return c; } } public class Main { public static void main(String args[]) { Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); } }
Inside the Test class, a
uses default access.
b
is specified as public
.
c
has private access.