tailieunhanh - Understanding static Methods and Data

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. | Understanding static Methods and Data In 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 the class itself not an object of type Math. So what s happening and how does this work You will often find that not all methods naturally belong to an instance of a class they are utility methods inasmuch as they provide a useful utility that is independent of any specific class instance. The Sqrt method is just such an example. If Sqrt were an instance method of Math you d have to create a Math object to call Sqrt on Math m new Math double d This would be cumbersome. The Math object would play no part in the calculation of the square root. All the input data that Sqrt needs is provided in the parameter list and the single result is returned to the caller by using the method s return value. Classes are not really needed here so forcing Sqrt into an instance straitjacket is just not a good idea. The Math 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 could have used in the Area method of the Circle class public double Area return radius radius In C all methods must be declared inside a class. However if you declare a method or a field 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 static method it does not have access to any instance fields defined for the class it can only use fields that are marked as static. Furthermore it can only directly invoke other methods in the class that are marked as static non-static instance methods require creating an object to call them