/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// Public vs private access.
using System;
class MyClass {
private int alpha; // private access explicitly specified
int beta; // private access by default
public int gamma; // public access
/* Methods to access alpha and beta. It is OK for a
member of a class to access a private member
of the same class.
*/
public void setAlpha(int a) {
alpha = a;
}
public int getAlpha() {
return alpha;
}
public void setBeta(int a) {
beta = a;
}
public int getBeta() {
return beta;
}
}
public class AccessDemo {
public static void Main() {
MyClass ob = new MyClass();
/* Access to alpha and beta is allowed only
through methods. */
ob.setAlpha(-99);
ob.setBeta(19);
Console.WriteLine("ob.alpha is " + ob.getAlpha());
Console.WriteLine("ob.beta is " + ob.getBeta());
// You cannot access alpha or beta like this:
// ob.alpha = 10; // Wrong! alpha is private!
// ob.beta = 9; // Wrong! beta is private!
// It is OK to directly access gamma because it is public.
ob.gamma = 99;
}
}
|