Const(常量) and Enum(枚举) in Java

Const

Why use Const in Java

cannot change once it has been assigned
代表常数,在程序运行过程中,值不能发生改变.
JVM和我们的应用程序都会缓存常量,因此使用常量可以提高性能。

Use Const

To define a variable as a constant, we just need to add the keyword “final” in front of the variable declaration.
要将变量声明为常量,需要在变量定义前面加“final”关键字,一旦定义,不能修改。
在Java编码规范中,要求常量名必须大写。
Example:

final float PI = 3.14f;

在程序中一旦将“pi”的值修改,会提示:Cannot assign a value of ‘PI’
可以先声明后定义:

final float PI;
PI = 3.14f
  • Java静态常量
    在项目中,一般都有很多静态常量,静态常量往往由于访问效率比较高。不过一般会把他们放在哪呢
    1、放到Interface,因为 Java interface中声明的字段在编译时会自动加上static final的修饰符,即声明为常量
    2、放到文件,如Properties文件
    3、放到Class,使用final String 。

第一跟第三种,会产生如下的问题:
那就是在Class 或者Interface定义的字符串常量 A = “a” 如果被其他类B使用了
这个时候如果想修改 A = “A” 则被之前被使用的其他类B必须重新编译才能生效
原因:常量,编译器是直接把常量赋给了B的使用处,并不是变量。所以对于常量A改变了, B使用A是不知道的。
解决方法:


private static final String a= "a";
        public static String getA(){
                return a;
        }

B使用的时候 就调用getA()函数,不过这样其实就比直接使用变量低效了一点点

  • Java局部常量
    放到Class里面使用final的的类型

Enum

why is Enum in Java

A Java Enum is a special Java type used to define collections of constants.
Java Enum是一种特殊的Java类型,用于定义常量集合。
More precisely, a Java enum type is a special kind of Java class.
更准确的说,Java enum类型是一种特殊的Java类。
An enum can contain constants, methods etc.
枚举可以包含常量、方法等。
Enum中的常量也需要大写。

Use

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}
  • Enum declaration can be done outside a Class or inside a Class but not inside a Method
//outside class
enum Color 
{ 
    RED, GREEN, BLUE; 
} 
  
public class Test 
{ 
    // Driver method 
    public static void main(String[] args) 
    { 
        Color c1 = Color.RED; 
        System.out.println(c1); //RED
    } 
}
//inside a class
public class Test 
{ 
    enum Color 
    { 
        RED, GREEN, BLUE; 
    } 
  
    // Driver method 
    public static void main(String[] args) 
    { 
        Color c1 = Color.RED; 
        System.out.println(c1); //RED
    } 
}
  • Every enum internally implemented by using Class

每个枚举在内部都是使用类实现的。

// internally above enum Color is converted to
class Color
{
     public static final Color RED = new Color();
     public static final Color BLUE = new Color();
     public static final Color GREEN = new Color();
}
  • Every enum constant represents an object of type enum.
    每个枚举常量都表示枚举对象。
  • enum type can be passed as an argument to switch statement.
// A Java program to demonstrate working on enum 
// in switch case (Filename Test. Java) 
import java.util.Scanner; 
  
// An Enum class 
enum Day 
{ 
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY; 
} 
  
// Driver class that contains an object of "day" and 
// main(). 
public class Test 
{ 
    Day day; 
  
    // Constructor 
    public Test(Day day) 
    { 
        this.day = day; 
    } 
  
    // Prints a line about Day using switch 
    public void dayIsLike() 
    { 
        switch (day) 
        { 
        case MONDAY: 
            System.out.println("Mondays are bad."); 
            break; 
        case FRIDAY: 
            System.out.println("Fridays are better."); 
            break; 
        case SATURDAY: 
        case SUNDAY: 
            System.out.println("Weekends are best."); 
            break; 
        default: 
            System.out.println("Midweek days are so-so."); 
            break; 
        } 
    } 
  
    // Driver method 
    public static void main(String[] args) 
    { 
        String str = "MONDAY"; 
        Test t1 = new Test(Day.valueOf(str)); 
        t1.dayIsLike();//Mondays are bad.
    } 
} 
  • Every enum constant is always implicitly public static final. Since it is static, we can access it by using enum Name. Since it is final, we can’t create child enums.
    每一个枚举常量总是public static final.。因为是 static,我们可以通过枚举名调用。,因为是final,所以不能创建子枚举。
  • We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt.
    可以在枚举中定义main方法。我们可以直接用命令提示符调用枚举。
// A Java program to demonstrate that we can have 
// main() inside enum class. 
enum Color 
{ 
    RED, GREEN, BLUE; 
  
    // Driver method 
    public static void main(String[] args) 
    { 
        Color c1 = Color.RED; 
        System.out.println(c1); //RED
    } 
} 
  • Enum and Inheritance :枚举和继承

  • All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.
    所有枚举继承java.lang.Enum class,作为一个class,只能继承一个父,所以一个枚举不能再继承别的任何父类。

  • values(), ordinal() and valueOf() methods :

  • These methods are present inside java.lang.Enum.

  • values() method can be used to return all values present inside enum.
    values()方法可以返回在枚举中的所有值

  • Order is important in enums.By using ordinal() method, each enum constant index can be found, just like array index.
    Order在枚举中很重要,使用ordinal()方法,可以返回枚举常量的索引,像数组索引一样。

  • valueOf() method returns the enum constant of the specified string value, if exists.
    valueOf()方法,返回指定字符串的枚举常量,如果指定的字符串存在。

/ Java program to demonstrate working of values(), 
// ordinal() and valueOf() 
enum Color 
{ 
    RED, GREEN, BLUE; 
} 
  
public class Test 
{ 
    public static void main(String[] args) 
    { 
        // Calling values() 
        Color arr[] = Color.values(); 
  
        // enum with loop 
        for (Color col : arr) 
        { 
            // Calling ordinal() to find index 
            // of color. 
            System.out.println(col + " at index "
                             + col.ordinal()); 
          // RED at index 0
		  //GREEN at index 1
          //BLUE at index 2
        } 
  
        // Using valueOf(). Returns an object of 
        // Color with given constant. 
        // Uncommenting second line causes exception 
        // IllegalArgumentException 
        System.out.println(Color.valueOf("RED")); //RED
        // System.out.println(Color.valueOf("WHITE")); 
    } 
} 
  • enum and constructor : 枚举和构造函数

  • enum can contain constructor and it is executed separately for each enum constant at the time of enum class loading.
    枚举可以包含构造函数,并且在加载枚举类的时候回分别加载每一个枚举常量。

  • We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.
    我们不能显式地创建枚举对象,因此不能直接调用枚举构造函数。

  • enum and methods :枚举和方法
    enum can contain both concrete methods and abstract methods. If an enum class has an abstract method, then each instance of the enum class must implement it
    枚举可以有具体方法实例方法,如果枚举类有抽象方法,那么每一个实例必须实现它。

// Java program to demonstrate that enums can have constructor 
// and concrete methods. 
  
// An enum (Note enum keyword inplace of class keyword) 
enum Color 
{ 
    RED, GREEN, BLUE; 
  
    // enum constructor called separately for each 
    // constant 
    private Color() 
    { 
        System.out.println("Constructor called for : " + 
        this.toString()); 
        //Constructor called for : RED
       //Constructor called for : GREEN
       //Constructor called for : BLUE
    } 
  
    public void colorInfo() 
    { 
        System.out.println("Universal Color"); 
    } 
} 
  
public class Test 
{     
    // Driver method 
    public static void main(String[] args) 
    { 
        Color c1 = Color.RED; 
        System.out.println(c1); //RED
        c1.colorInfo(); //Universal Color
    } 
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值