-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAccessDemo.java
More file actions
38 lines (31 loc) · 851 Bytes
/
AccessDemo.java
File metadata and controls
38 lines (31 loc) · 851 Bytes
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
29
30
31
32
33
34
35
36
37
38
// Public vs private access.
class MyClass {
private int alpha; // private access
public int beta; // public access
int gamma; // default access (essentially public)
/*
Methods to access alpha.
It is OK for a member of a class to access a private member of the smae class.
*/
void setAlpha(int a) {
alpha = a;
}
int getAlpha() {
return alpha;
}
}
class AccessDemo {
public static void main(String args[]) {
MyClass ob = new MyClass();
/*
Access to alpha is allowed only through its accessor methods.
*/
ob.setAlpha(-99);
System.out.println("ob.alpha is " + ob.getAlpha());
// You cannot access alpha like this:
// ob.alpha = 10; // Wrong! alpha is private!
// These are OK because beta and gamma are public.
ob.beta = 88;
ob.gamma = 99;
}
}