Interfaces vs. enums

前端 未结 5 1445
名媛妹妹
名媛妹妹 2021-02-07 00:24

Between interfaces and enums, which is better for declaring constants? Why is it so?

5条回答
  •  情深已故
    2021-02-07 00:58

    Just a code :

    public interface InterfaceForConstants() {
        String **TOTO** = "Et voilà !";
        double **PI** = 3.14159265358979323846;
    }
    

    Using :

    class ClasseName implements InterfaceForConstants () {
    
        String myString;
    
        if (myString.equals(**TOTO**) {
            // do something
        }
    
        double circumference = **PI** * diameter; // instead of MathConstants.PI * diameter;
    
    }
    

    Clean and simple. If something can do what you need, take the simplest one! Writing code by the rules is good, writing code that is easy to read is better, even if a rule is not respected. Think about when you have to read your code after a few months. If you want to be more specific, make a javadoc to explain it!

提交回复
热议问题