最终静态vs非最终静态变量? [英] final static vs non-final static variable?

查看:130
本文介绍了最终静态vs非最终静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道这两种方法的区别?

  public class SingleTone {

private static final instance = new SingleTone();

private SingleTone(){
}
public [static] SingleTone getinstance(){
return instance;
}
}

  public class SingleTone {

private static instance = new SingleTone();

private SingleTone(){
}
public [static] SingleTone getinstance(){
return instance;
}
}

我知道最终的静态变量是线程安全的,但是我找不到非最终的问题。
(注意:我正在寻找最终静态变量与非最终静态变量的差异,所以请不要建议如何实现Singleton设计模式,我知道有一个Enum方法。)



已编辑:我错过了static关键字现在已经修复了!

解决方案

除了可能的编译器优化之外,没有什么区别。在任何一种情况下,由于它是私有的,没有设置器,没有什么可以修改它,所以如果它是 final 不是特别重要。但是,在这两种情况下,您的 getInstance()方法需要声明为 static


Does any one know differences of this two approach?

public class SingleTone {

    private static final instance = new SingleTone();

    private SingleTone() {
    }
    public [static] SingleTone getinstance() {
        return instance;
    }
} 

and

public class SingleTone {

    private static instance = new SingleTone();

    private SingleTone() {
    }
    public  [static] SingleTone getinstance() {
        return instance;
    }
} 

I know final static variables are thread-safe however i can't find any problem with non-final one. (NOTE: I'm seeking the differences of final static variables with non-final static variables so please don't suggest how to implement the Singleton design pattern. I know there is an Enum approach.)

Edited: I missed static keyword on method now its fixed!

解决方案

There isn't much difference except possible compiler optimizations. In either case, because it's private with no setter, there's nothing that can modify it, so it doesn't particularly matter if it's final or not. However, in both cases, your getInstance() method needs to be declared static.

这篇关于最终静态vs非最终静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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