Java's access specifiers are public, private, protected and a default access level.
Here is an example for a public member variable
public int i;
The following code defines a private member variable and a private member method:
private double j;
private int myMethod(int a, char b) { // ...
To understand the effects of public and private access, consider the following program:
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) {
c = i;
}
int getc() {
return c;
}
}
public class Main {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 1;
ob.b = 2;
// This is not OK and will cause an error
// 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());
}
}
The output:
a, b, and c: 1 2 100
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |