Creating Interfaces

Tạo giao diện kế thừa từ một lớp học là một cơ chế mạnh mẽ, nhưng sức mạnh thực sự của di sản đến từ kế thừa từ một giao diện. Một giao diện cho phép bạn hoàn toàn riêng biệt tên của một phương pháp từ việc thực hiện | Creating Interfaces Inheriting from a class is a powerful mechanism but the real power of inheritance comes from inheriting from an interface. An interface allows you to completely separate the name of a method from its implementation. For example suppose you want to define a new collection class that allows you to store objects in a particular sequence. When you define the collection class you do not want to restrict the types of object that it can hold but you need to provide a way of sorting the objects into the specified sequence. The question is how do you provide a method that sorts objects whose types you do not know when you write the collection class At first glance this problem seems similar to the ToString problem described earlier and can be resolved by declaring a virtual method that other classes override. However this is not the case. There is not necessarily any form of inheritance relationship between the collection class and the objects that it holds so a virtual method would not be of much use. The solution is to specify that all objects in the collection must provide a method allowing them to be compared to each other such as the CompareTo method shown below int CompareTo object obj return 0 if this instance is equal to obj return 0 if this instance is less than obj return 0 if this instance is greater than obj . The collection class can then make use of this method to sort its contents. You can define an interface that includes this method and specify that the collection class will allow only classes that implement this interface as its contents. This mechanism guarantees that you will be able to call the CompareTo method on all objects in the collection and sort them. Interfaces allow you to truly separate the what from the how. The interface tells you only what the name return type and parameters of the method are. Exactly how the method is implemented is not a concern of the interface. The interface represents how you want an object to be .

Không thể tạo bản xem trước, hãy bấm tải xuống
TÀI LIỆU MỚI ĐĂNG
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.