什么时候应该在类中使用静态方法,这样做有什么好处? [英] When should I use static methods in a class and what are the benefits?

查看:215
本文介绍了什么时候应该在类中使用静态方法,这样做有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有静态变量的概念,但是静态方法在类中的好处是什么?我已经在一些项目上工作,但没有使方法成为静态方法.每当需要调用类的方法时,我都会创建该类的对象并调用所需的方法.

I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need to call a method of a class, I create an object of that class and call the desired method.

Q:方法中的静态变量即使在执行方法时仍保留其值,但只能在其包含方法中访问,但是静态方法的最佳定义是什么?

Q: Static variable in a method holds it's value even when method is executed but accessible only in its containing method but what is the best definition of static method?

问:是否在不创建该类对象的情况下调用静态方法是静态方法的唯一好处?

Q: Is calling the static method without creating object of that class is the only benefit of static method?

问:静态方法的可访问范围是多少?

Q: What is the accessible range for static method?

谢谢

推荐答案

您对静态变量的描述更适合C语言中的描述.面向对象术语中静态变量的概念在概念上有所不同.我是从Java经验中汲取经验的.当静态方法和字段在概念上不属于某个实例时,它们将非常有用.

Your description of a static variable is more fitting to that found in C. The concept of a static variable in Object Oriented terms is conceptually different. I'm drawing from Java experience here. Static methods and fields are useful when they conceptually don't belong to an instance of something.

考虑一个Math类,其中包含一些常见的值,例如Pi或e,以及一些有用的函数,例如sin和cos.创建单独的实例来使用这种功能确实没有任何意义,因此它们最好作为静态变量:

Consider a Math class that contains some common values like Pi or e, and some useful functions like sin and cos. It really does not make sense to create separate instances to use this kind of functionality, thus they are better as statics:

// This makes little sense
Math m = new Math();
float answer = m.sin(45);

// This would make more sense
float answer = Math.sin(45);

在OO语言中(同样,从Java角度来看),函数或更好地称为方法,不能具有静态局部变量.只有类可以具有静态成员,正如我已经说过的,与C中的静态概念相比,该成员几乎没有什么.

In OO languages (again, from a Java perspective) functions, or better known as methods, cannot have static local variables. Only classes can have static members, which as I've said, resemble little compared to the idea of static in C.

这篇关于什么时候应该在类中使用静态方法,这样做有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆