Previous Page
Next Page

Controlling Accessibility

Surprisingly, the Circle class is currently of no practical use. When you encapsulate your methods and data inside a class, the class forms a boundary to the outside world. Fields (such as radius) and methods (such as Area) defined in the class can be seen by other methods inside the class, but not by the outside world—they are private to the class. In other words, although you can create a Circle object in a program, you cannot access its radius field or call its Area method, which is why the class is not of much use—yet! However, you can modify the definition of a field or method with the public and private keywords to control whether it is accessible from the outside:

Here is the Circle class again. This time Area is declared as a public method and radius is declared as a private field:

class Circle 
{ 
    public double Area()  
    { 
        return 3.141592 * radius * radius;  
    } 
  
    private double radius; 
}
NOTE
C++ programmers should note that there is no colon after the public or private keywords. You must repeat the keyword on every declaration.

Note that radius is declared as a private field; it is not accessible from outside the class. However, radius is accessible from inside the Circle class. This is why the Area method can access the radius field; Area is inside the Circle class, so the body of Area has access to radius. However, the class is still of limited value as there is no way of initializing the radius field. To fix this, we will use a constructor.

TIP
The fields in a class are automatically initialized to 0, false, or null depending on their type. However, it is still good practice to provide an explicit means of initializing fields.
IMPORTANT
Don't declare two public class members whose names differ only in case. If you do, your class will not conform to the Common Language Specification (CLS), and will not be usable from other languages that are not case sensitive, such as Microsoft Visual Basic.

Previous Page
Next Page