Danh mục tài liệu

Understanding static Methods and Data

Số trang: 6      Loại file: pdf      Dung lượng: 25.78 KB      Lượt xem: 18      Lượt tải: 0    
Xem trước 2 trang đầu tiên của tài liệu này:

Thông tin tài liệu:

Hiểu biết về phương pháp tĩnh và dữ liệu Trong bài tập trước đó bạn đã sử dụng phương pháp Sqrt của lớp Toán. Nếu bạn nghĩ về nó, cách mà bạn gọi là phương pháp được hơi lẻ. Bạn viện dẫn các phương pháp trên lớp chính nó, không phải là một đối tượng của loại Math.
Nội dung trích xuất từ tài liệu:
Understanding static Methods and Data Understanding static Methods and DataIn the previous exercise you used the Sqrt method of the Math class. If you think about it,the way in which you called the method was slightly odd. You invoked the method on theclass itself, not an object of type Math. So, whats happening and how does this work?You will often find that not all methods naturally belong to an instance of a class; theyare utility methods inasmuch as they provide a useful utility that is independent of anyspecific class instance. The Sqrt method is just such an example. If Sqrt were an instancemethod of Math, youd have to create a Math object to call Sqrt on:Math m = new Math();double d = m.Sqrt(42.24);This would be cumbersome. The Math object would play no part in the calculation of thesquare root. All the input data that Sqrt needs is provided in the parameter list, and thesingle result is returned to the caller by using the methods return value. Classes are notreally needed here, so forcing Sqrt into an instance straitjacket is just not a good idea. TheMath class also contains many other mathematical utility methods such as Sin, Cos, Tan,and Log. Incidentally, the Math class also contains a utility field called PI that we couldhave used in the Area method of the Circle class: public double Area() { return Math.PI * radius * radius; }In C#, all methods must be declared inside a class. However, if you declare a method or afield as static, you can call the method or access the field by using the name of the class.No instance is required. This is how the Sqrt method of the real Math class is declared:class Math{ public static double Sqrt(double d) { ... } ...}Bear in mind that a static method is not called on an object. When you define a staticmethod, it does not have access to any instance fields defined for the class; it can only usefields that are marked as static. Furthermore, it can only directly invoke other methods inthe class that are marked as static; non-static (instance) methods require creating anobject to call them on first.Creating a Shared FieldAs mentioned in the previous section, you can also use the static keyword when defininga field. This allows you to create a single field that is shared between all objects createdfrom a single class, (non-static fields are local to each instance of an object). In thefollowing example, the static field NumCircles in the Circle class is incremented by theCircle constructor every time a new Circle object is created:class Circle{ public Circle() // default constructor { radius = 0.0; NumCircles++; } public Circle(double initialRadius) // overloaded constructor { radius = initialRadius; NumCircles++; } ... private double radius; public static int NumCircles = 0;}All Circle objects share the same NumCircles field, and so the statement NumCircles++;increments the same data every time a new instance is created. You access theNumCircles field specifying the Circle class rather than an instance. For example:Console.WriteLine(Number of Circle objects: {0}, Circle.NumCircles);TIPStatic methods are also called class methods. However, static fields tend not to be calledclass fields; theyre just called static fields (or sometimes static variables).Creating a static Field with the const KeywordYou can also declare that a field is static but that its value can never change by prefixingthe field with the const keyword. Const is short for “constant.” A const field does not usethe static keyword in its declaration, but is nevertheless static. However, for reasons thatare beyond the scope of this book to describe, you can declare a field as const only whenthe field is an enum, a primitive type, or a string. For example, heres how the real Mathclass declares PI as a const field (it declares PI to many more decimal places than shownhere):class Math{ ... public const double PI = 3.14159265358979;}Static ClassesAnother feature of the C# language is the ability to declare a class as static. A static classcan contain only static members (all objects that you create using the class will share asingle copy of these members). The purpose of a static class is purely to act as a holder ofutility methods and fields. A static class cannot contain any instance data or methods, andit does not make sense to try and create an object from a static class by using the newoperator. In fact, you cant actually create an instance of an object using a static class byusing new even if you wanted to (the compiler will report an error if you try). If you needto perform any initialization, a static class can have a default constructor, as long as it isalso declared as static. Any other types of constructor are illegal and will be reported assuch by the compiler.If you were defining you own version of the Math class, containing only static members,it could look like this:public static class Math{ public static double Sin(double x) {…} public static double Cos(double x) {…} public static double Sqrt(double x) {…} ...}Note, however, that the real Math class is not defined this way as it actually does havesome instance methods.In the final exercise in this chapter, you will add a private static field to the Point classand initialize the field to 0. You will increment this count in both constructors. Finally,you will write a public static method to return the value of this private static field. Thisfield will enable you to find out how many Point objects have been created.Write static members and call static methods1. Using Visual Studio 2005, display the Point class in the Code and Text Editor window.2. Add a private static field called objectCount of type int to the end of the Point class. Initialize it to 0 as you declare it. The Point class sh ...