19th: interfaces are only used to define types
This article provides a counter-example, saying that some interfaces contain only constants. This is a bad use of the interface. To implement the same functionality, you should use a tool class that cannot be instantiated (4th).
Public classphysicalconstants {Privatephysicalconstants () {}//Prevents instantiation//Avogadro ' s number (1/mol) Public Static Final DoubleAvogadros_number = 6.02214199e23; //Boltzmann constant (j/k) Public Static Final DoubleBoltzmann_constant = 1.3806503e-23; //Mass of the Electron (kg) Public Static Final DoubleElectron_mass = 9.10938188e-31;}
In addition, we have learned that if you use it a lot, you need to always call it in a similar physicalconstants.avogadros_number way. At this point, you can use the static import mechanism of Java (just a little trick). is to use the import static Com.effectivejava. physicalconstants.* the way the class is imported, you can then use the constant avogadros_number directly, without having to add the class name.
Reference http://www.cnblogs.com/mengdd/archive/2013/01/23/2873312.html
20th: Class hierarchy is better than label class
This is also an example of a counter (label class).
classFigure {enumShape {RECTANGLE, CIRCLE}; Finalshape shape; //rectangles have long and wide Doublelength; Doublewidth; //round with Radius Doubleradius; Figure (Doubleradius) {Shape=shape.circle; This. Radius =radius; } figure (DoubleLengthDoublewidth) {Shape=Shape.rectangle; This. length =length; This. width =width; } DoubleArea () {Switch(shape) { CaseRECTANGLE:returnLength *width; CaseCIRCLE:returnMath.PI * (RADIUS *radius); default: Throw NewAssertionerror (); } }}
View Code
This class can represent a circle or a rectangle. But the level is not clear, very messy.
The correct implementation, that is, our common implementation, should be to write a graph class as a base class, and then the Circle class and the rectangle class are implemented separately.
Abstract classFigure {Abstract DoubleArea ();}classCircleextendsFigure {Final Doubleradius; Circle (Doubleradius) { This. Radius =radius; } DoubleArea () {returnMath.PI * (RADIUS *radius); }}classRectangleextendsFigure {Final Doublelength; Final Doublewidth; Rectangle (DoubleLengthDoublewidth) { This. length =length; This. width =width; } DoubleArea () {returnLength *width; }}
Effective JAVA2 reading notes-classes and Interfaces (iv)