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

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

问题描述

所以我的程序员朋友讨厌使用 static 编码.然而,我的 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();

t1t2 都将拥有自己的 x 副本.

Both t1 and t2 will have its own copy of x.

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

例如:

public class Test{

   public static int x = 5;

 }

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

t1t2 都将正好有一个 x 在它们之间共享.

3. JVM 加载类时初始化静态变量.

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

4. 静态方法 不能访问非静态变量或方法.

5. 静态方法连同静态变量可以模仿一个单例模式>,但是这不是正确的方法,因为当类很多时,我们无法确定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天全站免登陆