主类中只有Java的静态成员 [英] Java only static members in main class

查看:89
本文介绍了主类中只有Java的静态成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在包含main方法的类中将该类的所有成员声明为静态成员是一种不好的做法吗?如果是这样,为什么?可以说,在main方法中,最好创建一个封闭类的新实例,然后从构造函数运行程序吗?

Is it bad practice to, in the class which contains the main method, declare all members of that class as static? If so, why? Is it better to, in the main method, create a new instance of the enclosing class, and run the program from the constructor so to speak?

编辑 :(澄清) 我知道有关静态和单例以及通常何时使用它的概念.但是这个问题专门针对程序的主类. @Andrew Tobilko(显然删除了他的答案..)从他的答案看来似乎最能理解我的问题.在我的情况下,我的主类约为200 LOC,并且它使用其他两个小类(每个< 100 LOC),因此它是一个小程序.主类包含创建一个Swing GUI和一些正在运行的逻辑,没有什么需要有几个实例,因此我认为我可能只是将所有内容设为静态,以便能够使用静态主方法中的所有内容.这是动机吗?一位用C#编写代码的朋友告诉我,使用大量静态代码将意味着C#会被判处死刑.它可能有内存问题吗?

(clarification) I know the concept about static and singletons and generally when to use it. But this question regards specifically the main-class of a program. @Andrew Tobilko (who apparently removed his answer..) seems to have best understood my question judging from his answer. In my case, my main-class is about 200 LOC, and it uses two other small class (< 100 LOC each), so it's a small program. The main-class contains creating a Swing GUI and some running logic, nothing which there needs to be several instances of, so I thought I might just make everything static, to be able to use everything from the static main-method. Is this motivated? A friend who codes in C# told me using a lot of static would mean death penalty in C#. Can there be some memory problems with it or something?

推荐答案

这不是更好"的选择-它取决于您需要执行的操作. 将一个类的所有成员声明为静态的(包括方法)仅会使该类变成单例.如果这是您的用例,那么是.

It's not 'better' - it depends on what you need to do. Declaring all the members of a class as static (including methods) simply turns the class into a singleton. If that's your use-case, then yes.

将属性声明为静态意味着该类的所有实例共享该属性的一个副本.

Declaring an attribute as static means that there is only one copy of this attribute which is shared by all the instances of the class.

如果您的用例需要创建多个实例,并且这些对象中的每个对象都应具有其属性的自己的私有副本",则您不应将该属性声明为静态.

If your use-case requires creating multiple instances, and each one of these objects should have its own "private copy" of an attribute then you shouldn't declare that attribute as static.

建议您先详细了解继续实施.

这篇关于主类中只有Java的静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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