Microsoft Visual C# 2010 Step by Step (P7)

Tham khảo sách 'microsoft visual c# 2010 step by step (p7)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 270 Part II Understanding the C Language Duplication in code is a warning sign. If possible you should refactor the code to avoid this duplication and reduce any maintenance costs. One way to achieve this refactoring is to put the common implementation into a new class created specifically for this purpose. In effect you can insert a new class into the class hierarchy. For example class GrazingMammal Mammal IGrazable void Chewing grass common code for chewing grass class Horse GrazingMammal ILandBound class Sheep GrazingMammal ILandBound This is a good solution but there is one thing that is still not quite right you can actually create instances of the GrazingMammal class and the Mammal class for that matter . This doesn t really make sense. The GrazingMammal class exists to provide a common default implementation. Its sole purpose is to be inherited from. The GrazingMammal class is an abstraction of common functionality rather than an entity in its own right. To declare that creating instances of a class is not allowed you must explicitly declare that the class is abstract by using the abstract keyword. For example abstract class GrazingMammal Mammal IGrazable If you try to instantiate a GrazingMammal object the code will not compile GrazingMammal myGrazingMammal new illegal Abstract Methods An abstract class can contain abstract methods. An abstract method is similar in principle to a virtual method which you met in Chapter 12 except that it does not contain a method body. Chapter 13 Creating Interfaces and Defining Abstract Classes 271 A derived class must override this method. The following example defines the DigestGrass method in the GrazingMammal class as an abstract method grazing mammals might use the same code for chewing grass but they must provide their own implementation of the DigestGrass method. An abstract method is useful if it does not make sense to provide a default implementation in the .

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.