本文介绍了如何在 Java 中声明一个常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们总是写:

public static final int A = 0;

问题:

  1. static final 是在类中声明 constant 的唯一方法吗?
  2. 如果我写 public final int A = 0; 代替,A 仍然是 constant 还是只是 instance 字段?
  3. 什么是实例变量?实例变量实例字段有什么区别?
  1. Is static final the only way to declare a constant in a class?
  2. If I write public final int A = 0; instead, is A still a constant or just an instance field?
  3. What is an instance variable? What's the difference between an instance variable and an instance field?

推荐答案

  1. 您可以在 Java 5 及更高版本中使用 enum 类型来实现您所描述的目的.它是类型安全的.
  2. A 是一个实例变量.(如果它有 static 修饰符,那么它就变成了一个静态变量.)常量只是意味着值不会改变.
  3. 实例变量是属于对象而非类的数据成员.实例变量 = 实例字段.
  1. You can use an enum type in Java 5 and onwards for the purpose you have described. It is type safe.
  2. A is an instance variable. (If it has the static modifier, then it becomes a static variable.) Constants just means the value doesn't change.
  3. Instance variables are data members belonging to the object and not the class. Instance variable = Instance field.

如果您在谈论实例变量和类变量之间的区别,则每个创建的对象都存在实例变量.而无论创建的对象数量如何,类变量每个类加载器只有一个副本.

If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.

Java 5 及更高版本 enum 类型

Java 5 and up enum type

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public String toString(){
    return this.color;
  }
}

如果您希望更改您创建的枚举的值,请提供一个 mutator 方法.

If you wish to change the value of the enum you have created, provide a mutator method.

public enum Color{
 RED("Red"), GREEN("Green");

 private Color(String color){
    this.color = color;
  }

  private String color;

  public String getColor(){
    return this.color;
  }

  public void setColor(String color){
    this.color = color;
  }

  public String toString(){
    return this.color;
  }
}

访问示例:

public static void main(String args[]){
  System.out.println(Color.RED.getColor());

  // or

  System.out.println(Color.GREEN);
}

这篇关于如何在 Java 中声明一个常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:44