Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (17.41 KB, 2 trang )
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:
•
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;
}