溫馨提示×

java接口如何定義常量

小億
82
2024-09-25 23:51:06
欄目: 編程語言

在Java接口中,不能直接定義常量,因?yàn)榻涌谥械乃蟹椒ǘ际请[式抽象的,常量需要在實(shí)現(xiàn)類中定義。但是,你可以在接口中定義一個靜態(tài)常量,這樣實(shí)現(xiàn)類就可以共享這個常量了。下面是一個示例:

public interface MyInterface {
    // 定義一個靜態(tài)常量
    public static final String CONSTANT = "Hello, World!";
}

實(shí)現(xiàn)這個接口的類可以這樣使用這個常量:

public class MyClass implements MyInterface {
    public void myMethod() {
        System.out.println(MyInterface.CONSTANT);
    }
}

0