Java静态与实例 [英] Java Static vs Instance

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

问题描述

所以我的编码器朋友讨厌使用静态编码。然而我的Java程序充满了它在类之间的链接,我有很多它们!

So my coder friend hates using the static coding. Yet my Java program is full of it to link between classes, and I have a lot of them!

是否值得重写整个代码来删除静态方法?

Is it worth rewriting the whole code to remove the static method?

使用一个优于另一个优势吗?

Is there any advantage of using one over the other?

推荐答案

1。实例变量每个对象一个,每个对象都有自己的实例变量副本。

1. An instance variable is one per Object, every object has its own copy of instance variable.

例如:

public class Test{

   int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

t1 t2 拥有自己的副本 x

2. 静态变量每个类一个,该类的每个对象共享相同的静态变量。

例如:

public class Test{

   public static int x = 5;

 }

Test t1 = new Test();   
Test t2 = new Test();

t1 t2 在它们之间共享一个x。

3。当JVM加载类时,初始化静态变量。

3. A static variable is initialized when the JVM loads the class.

4。 A 静态方法 无法访问非静态变量或方法。

4. A static method cannot access Non-static variable or method.

5。 静态方法以及静态变量可以模仿 a 单例模式,但它不是正确的方式,就像有很多类的时候一样,我们无法确定类的加载顺序JVM,这可能会产生问题。

5. Static methods along with Static variables can mimic a Singleton Pattern, but IT'S NOT THE RIGHT WAY, as in when there are lots of classes, then we can't be sure about the class loading order of JVM, and this may create a problem.

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

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