Some constants are used in a software system, and a popular practice is to define the relevant constants in a dedicated constant interface, for example:
Package com. Finalinterface; Public Interface myconstants { publicstaticfinaldouble math_pi = 3.1415926; publicstaticfinaldouble math_e = 2.71828;}
The following circle classes require access to the above Math_pi constants, one in the form of "My-constants.math_pi", as follows:
Package com. Finalinterface; Public class Circle { privatedouble R; radius public Circle (double r) { this. R= r; } Public Double getcircumference () { return 2 * r * myconstants.math_pi; }}
Another way is to have the Myconstants interface implemented in the Circle class, as follows:
InPort mypack.myconstants; Public class Circle inplenments myconstants{ privatedouble R; Public Circle (double r) {this. rar;} Public double getcircumference () {return * * R * math_pi;} Public double Getarea () {return r*r * math_pi;}}
The second way that the Circle class inherits the constants of the Myconstants interface, you can reference the constant name directly in the program, but this violates the object-oriented encapsulation idea, the MATH_PI constant is part of the implementation details of the Circle class and is only used to calculate the perimeter and circle area of the circle. , there is no need to expose Math_pi constants to the outside world. This is actually a disclosure of the implementation of the behavior, will be the maintainability of the system. In JDK1.5, because of the import static statement, it allows the class to directly access static constants in another interface B or Class B without specifying the name of interface B or Class B, and Class A does not need to implement Interface B or inherit Class B. As follows:
Packagecom. Finalinterface;Import StaticCom. finalinterface.myconstants.*; Public classCircle {Private DoubleR//radius PublicCircle (DoubleR) { This. R =R; } Public Doublegetcircumference () {return2 * R *Math_pi; }}
The import static statement simplifies programming and prevents the circle class from inheriting and exposing static constants in Myconstants.
Constant interface mode