Public vs private access : Class Access Modifiers « Class Interface « C# / C Sharp






Public vs private access

Public vs private access
/*
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;  
   }  
}

           
       








Related examples in the same category

1.Using Access Modifiers
2.Member Accessibility
3.Member Hiding
4.Demonstrate protectedDemonstrate protected
5.illustrates member accessibilityillustrates member accessibility
6.illustrates member hidingillustrates member hiding
7.Illustrates the use of various access modifiersIllustrates the use of various access modifiers