java - public static final 定义的变量是用来干什么的?
PHP中文网
PHP中文网 2017-04-18 10:28:39
0
6
611

我在项目中看到一个类里定义的变量都是public static final的,问了一下同事说是常量类,为什么要这么定义呢?是因为static是全局的,final是不可修改的吗?那这和定义一个private变量再定义一个get方法有什么区别?

PHP中文网
PHP中文网

认证0级讲师

reply all(6)
大家讲道理

Answer the question first

  • static is to make it a member of a class, not an object, so it is convenient to use

  • public is for easy access

  • final means that this is a constant and cannot be modified

  • Private objects, and then define get and set for access control, which is a conventional encapsulation

  • To sum up, public static final can make access very convenient and will not be modified. Generally, configuration information can be placed, as well as some status code definitions.

Other additions:

  • The static modified object is placed under the root of the reference, which means it will almost never be recycled

洪涛

static is static. Variables modified by static can be called directly using the class name and variable name without the need to refer to the instantiated object of the class.
final modified variables are mostly used to declare a constant when the variable is first used. After the first assignment, this variable is equivalent to a constant or can be understood as the value of this variable is fixed and the value cannot be modified

迷茫

Global constants. For example, the global configuration of the project can be modified with public static final

刘奇

Private is defined and cannot be accessed from other classes. So what's the point of such a constant definition?

伊谢尔伦

Static constants, give me an example

public class Constant {

    public static final int DEAFULT_TAG = 0xcc33;

    public static final int DEFAULT_VERSION = 1;


    public static final Long PHOTO_PRICE = 1L;


    public static final String OSS_STYLE = "?x-oss-process=style/photo_printer";
}

The above Constantas a constant class, when I need to call constants in various other places

Just use Constant.OSS_STYLE directly

阿神

To put it bluntly, it is to facilitate access and increase code readability. There is not much difference in performance.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!