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

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

问题描述

我有静态变量的概念,但是类中的静态方法有什么好处.我参与了一些项目,但我没有将方法设为静态.每当我需要调用类的方法时,我都会创建该类的对象并调用所需的方法.

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: 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天全站免登陆