公共静态方法与公共方法
公共静态方法和公共方法有什么区别?为什么要使用公共静态方法?
What's the difference between a public static method and a public method? Why would you use a public static method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Math 类的方法是静态的。因此,在执行
Math 类本身时,您所做的不会改变 - 它仅返回一个值或根据您传递的值进行操作。
所以 - 静态方法对于实用程序很有用。像
or
这样的事情 使用静态方法来处理其他事情是很不寻常的。不要使用像“getInstance()”这样的静态方法来创建单例——而是研究依赖注入的框架。
The methods of the Math class are static. So, in doing
the Math class itself is unchanged by what you've done - it only returns a value or acts upon the value you pass.
So - static methods are useful for utilities. Things like
or
It's very unusual that you'd use a static method for anything else. Don't use statics like 'getInstance()' to create Singletons - look into a framework for dependency injection instead.
静态方法是不特定于类(对象)的任何实例的方法,它们是不允许包含 this 引用的方法,您可以直接通过类(而不是对象实例)访问它们
static methods are methods that a not specific to any instance of a class (object) they are methods that are not allowed to contain this references and you can access them through the class directly (not the object instances)
静态方法可以用作重载构造函数。 ActionScript 没有函数重载,所以有时我会写这样的内容:
Static methods can be used as overloaded constructors. ActionScript doesn't have function overloading, so sometimes I'm writing something like:
为了使您的概念清晰,假设您想知道您的类已实例化多少次,则每次创建对象时,您将在类构造函数中使用静态变量 counter 。
然后你必须使用静态方法来访问这些数据,否则你可以将变量声明为 public 或 default 并使用类名访问它,但这违反了 OOP 原则。 小例子
这是公共类 CAR 的
{
私有静态变量计数器:int=0;
私有函数 CAR(){ Counter++; }
公共静态函数 ReturnTotalCarInstances():int
{
退货柜台;
静态变量
有其优点,
这就是大多数编程语言中提供静态变量的原因。计算实例是静态变量的一个小用途。它们的使用范围要大得多。要点是它用于在类的所有对象之间全局共享数据。
To make your concept clear, Suppose if you want to know how many times your class has been instantiated, you will be using static variable counter in your class constuctor, each time your object is created.
Then you have to use static method to access this data else you can declare your variable public or default and access it with class name but that violates the OOP principals. here is the little example
public class CAR
{
private static var Counter:int=0;
private function CAR(){ Counter++; }
public static function ReturnTotalCarInstances():int
{
return Counter;
}
}
Static variables have their benefit thats why it is provided in most programming languages. Counting instances is the small use of static variable. They are used in much bigger scope. The main point is it is used to share data globally among all objects of Class.