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 se
Trang 1Controlling 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:
• A method or field is said to be private if it is accessible only from the inside of the
class To declare that a method or field is private, you write the keyword private before its declaration This is actually the default, but it is good practice to
explicitly state that fields and methods are private to avoid any confusion
• A method or field is said to be public if it is accessible from both the inside and
the outside of the class To declare that a method or field is public, you write the keyword public before its declaration
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
Trang 2TIP
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