Home  >  Q&A  >  body text

java - public static final 定义的变量是用来干什么的?

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

PHP中文网PHP中文网2718 days ago615

reply all(6)I'll reply

  • 大家讲道理

    大家讲道理2017-04-18 10:30:39

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:30:39

    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

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:30:39

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

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:30:39

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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:30:39

    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

    reply
    0
  • 阿神

    阿神2017-04-18 10:30:39

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

    reply
    0
  • Cancelreply