Bamboo shoots fried meat Reprinted - Read "Effective Java Chinese" (2)

xiaoxiao2021-03-06  74

From bamboo shoots fried meat http://hedong.3322.org/ Read "Effective Java Chinese" (11) Article 10: Carefully Rewriting Clone

The purpose of the Cloneable interface is a MIXIN interface for the object, indicating that such objects are allowed to be cloned. Cloneable does not contain any way, just determines the behavior implemented by the protected Clone method in Object: If a class implements Cloneable, the Object's Clone method returns a domain copy of the object, otherwise a ClonyNotsupportedException is throwing an exception. As for Clone itself, it is a very risky, language-free object creation mechanism: no need to call constructor to create a function. The convention for the Clone method is: Create and return to an object, and

X.Clone! = x is true, x.clone (). getClass () == x.getClass () is true, x.clone.equals (x) is true, of course, these three are not absolute requirements. If you have rewritten a non-final class's Clone method, you should return an object obtained by calling super.clone. If all of the superclars of a class comply with this rule, then the super.clone will eventually call the client's clone method to create an instance of the correct class. This mechanism is roughly similar to the automatic constructor chain, but it is not forced to require. In fact, the Clone method is another constructor that you must ensure that it does not hurt the original object and correctly establishes a constraint relationship in the cloned object. The clone structure is incompatible with the normal use of the Final domain that points to variable objects. This variable object can be safely shared between the original object and the clone object. In order to make a class becomer, it may be necessary to remove the Final modifier from some domains. A good way to achieve object copies is to provide a copy constructor (the type of the unique parameter is a class containing the constructor). Cloneable has so many questions, and other interfaces should not expand the interface, and the classes designed to inherit (see Article 15) will implement this interface.

Read "Effective Java Chinese" (12) No. 11: Consider implementing the Comparable Interface CompareTo method is not declared in Object, it is the only method in the java.lang.comPareable interface. A class implements the Compareable interface, which indicates that its instance has an intrinsic order relationship (Natural Ordering). If an object in an array implements a Compareable interface, sort this array is very simple: arrays.sort (); is very simple to store Comareable objects stored in a collection. Once your class implements a Compareable interface, it can cooperate with many generic algorithm and operational implementation of the set of the interface to obtain a powerful function with a small effort. All value classes in the Java platform library implements a Compareable interface.

CompareTo's agreement is: compare the current object to the specified object, when the object is less than, equal to or greater than the specified object, then returns a negative integer, 0 or positive integer, and throws the ClassCastException exception if compared .

The implementator must ensure that SGN (X.Compareto (Y)) is met for all X and Y, and if the former throws it, it will throw.

Implementors must guarantee that the comparison relationship can be passed: X.Compareto (Y)> 0 and Y.com Gueto (z)> 0 Implementors must guarantee X.Compareto (Y) == 0 Contact: For all Z, SGN (X.Compareto (Z)) == SGN (Y.Compareto (Z))

Strong proposal (X.Compareto (Y) == 0) == (x.equals (y)), for classes that implement the Compareable interface, if it violates this condition, it should be clearly stated.

Unlike Equals, Comapreto can do not compare when crossing different classes. Depending on the comparisonal relationship includes an ordered collection class Treeset and TreeMap, and tool class collections and arrays, each of them contains search and sorting algorithms. Similar to Equals, Compareto also follows: self-translocation, symmetry, transfer, non-void. Also, there is no simple manner that it can be done when extending a newly actually calibrated class, which increases new features while maintaining the Compareto convention.

Read "Effective Java Chinese" (13) Article 12: Make the accessibility of the accessibility of the class and members to minimize a good module hidden all implementation details, separating its API clearly separated from the implementation. Communication between modules is only communicated by their API, and a module does not need to know the internal work of other modules, which is an information hidden or encapsulation. The reason why this is to effectively relieve the coupling relationship between the modules in a system, and the cost is the sacrifice of performance.

Accessibility of an entity (class, interface, member, etc.) in Java, is declared by the entity declaration, and the access modifiers (private protected and public) that appear in the entity declaration. Experience shows that a class or member should not be accessed by an external world, that is, the minimum possibility should be used, and the level of access is consistent with the correct functionality of the software. "Make an unnecessary public class becomes a class private class." For top-level (non-nest) classes and interfaces, there are only two possible access levels: packages private and public. To make a class or interface, it is part of the implementation of the package, not part of the package, so that it can be freely modified in the future; if it makes public, it is obliged to support it forever. . If a package-level private top-level or interface is only internally used in a certain class, you should consider making it as a private nested class (or interface). There are four possible access levels for members (domain, methods, nested classes, and nested interfaces), accessible incremental order:

Private (Private) - Only accessible private (Package-private) only in the class (when not explicitly specifying modifier), any class inside any class can access protected (protected) - Accessible (public) - anywhere can be accessed anywhere

Protected members are part of a class of exported APIs that must be supported forever, and protected members should be as few as possible. If a method rewrites a method in the superclass, the access level of the method in the subclass is lower than the level in the superclass is not allowed. The public class should reduce the public domain as much as possible. The classes containing public variable domains (Final domains of public non-final domains or publicly variable objects) are not threads. One exception is that the constant of exposed the class is permitted by the public static Final field. It is almost always wrong with the public static final array domain. Such as: // Protential Security Hole! Public static Fina Type [] VALUES = {...}; should be replaced with a private array, as well as a public non-variable list, such as private static type [] private_values ​​= {. .. Public static final type [] value () {return (type [] private_values.clone ());}; read "Effective Java Chinese" (14) Section 13: Support non-variable non-variable class It is a simple class that cannot be modified. All information included in each instance must be provided when the instance is created and fixed in the entire survival of the object. Such as Java's String class, primitive type packaging, Biginteger, and BigDecimal, etc.

5 rules of non-variable classes:

Do not provide any ways to modify the object (also known as Mutator) to ensure that there is no way to be rewritten, the general approach is to make all domains that make all domains make all domains into private guarantees for any variable. The mutual exclusion of components. If the class has a domain that points to a variable object, you must ensure that the class of the class cannot get a reference to these objects, and never use the object reference to the customer to initialize such a domain, and do not provide a reference to returning such references. method. Use protective copy technologies in the constructor, access method, and readObject method (see section 24).

Look at a "plural" example: public final class complex {private final float re ;. Private Final Fload im;

Public Complex (Float Re, Float IM) {this.re = Re; excitation float realpart () {Return Re;

Public Complex Add (COMPLEX C) {RETURN New Complex (Re C.RE, IM C.IM);} public complex subtract (complex new complex (Re-c.re, IM-c.im) PUBLIC Complex Multiply (Complex C) {RETURN New Complex (RE * C.RE-IM * C.IM, RE * C.IM IM * C.RE);} Public Complex Divide (Complex C) {Float TMP = C.RE * C.RE C.IM * C.IM; RETURN NEW Complex ((RE * C.RE IM * C.IM) / TMP, (iM * C.RE-RE * C.IM) / TMP);} public boolean Euqals (Object O) {if (o == this) Return True; if (! (o instanceof complex) Return False; complex c = (complex) o; return (float.floattoinTbits (RE ) == float.floattoinTbits (c.re)) && float.floattointBits (IM) == float.floatthannelBits (c.im));} public int hashcode () {int result = 17 float.floattoinTbits (RE); Result = 37 * Result float.floattoinTbits (IM); returnrate;} public string toString () {return "(" RE " " IM "i)";}} // This Complex definition is a non-industrial stage The plural implementation, one is because the implementation of the division can cause incorrect rounding, and the other is no case in which the plural NAN or infinity is not processed. In this example, the completion of the plurality of operations returns a new instance, not the original example, which is called functional, and the corresponding process method (Precedural) of the modified instance status (Precedural) . Non-variable objects are relatively simple, it is essentially thread safe, they do not require synchronization, so non-variable objects can be freely shared (a simple practice, is to provide public static Final constants), without Protective copying, but also provides a CLONE method or copy constructor (such as copy constructor of the String class). Not only can you share non-variable objects, but also you can share their internal information. For example, the Biginteger's Negate method generates a new instance, and the array of stored values ​​is the same as the original instance. Non-variable objects are other objects - whether variable or non-variable - BUILDIG BLOCK. The unique disadvantage of non-variable classes is that a separate object is required for each different value. Common Solutions is to provide a variable matching class, such as String configuration variable class StringBuffer. A class is never allowed to rewrite the sub-class rewriting. There are three: declaration class Final, see the precedent class is not final, but each The method is Final, which is not worth promoting all constructor to be private or packaged private, and increase the public static factories to replace the public constructor.

Such as: // Immutable class with static factories instead of construtorspublic class Complex {private final float re; private final float im; private Complex (float re, float im) {this.re = re; this.im = im;} public static Complex Valueof (Float Re, Float IM) {Return New Complex (RE, IM);} ...} This method is strong, it is worth promoting. Due to historical reasons, the Biginteger or BigDecimal method can be rewritten, so when you develop your own non-variable class, if you don't make sure you receive non-variability of these two classes, you need to make a protective copy. Such as: public void foo (BIGINTEGER B) {IF (B.getClass ()! = Biginteger.class) B = New Biginteger (B.TobyteaRray ()); ...} In fact, the rules mentioned earlier are too strong, only Need to be met: No method can generate an external visible to the object state (External ". For example: // Cached, lazily initialized function of an immutable objectprivate volatile Foo cachedFooVal = UNLIKELY_FOO_VALUE; public Foo foo () {Foo result = cachedFooVal; if (result == UNLIKELY_FOO_VALUE) result = cachedFooVal = fooVal (); return result;} / / Fooval function is overhead, so the technique of slowing initialization is used in front. Private foo fooval () {...} Unless there is a good reason to make a class becomes a variety of categories, it should be non-variable, the disadvantages are performance issues, and if the performance requirements are relatively high, public can be provided Matching class. If a class cannot be made non-variable classes, it should still be possible to limit its variability as much as possible. The constructor should create a fully initialized object, and all constraints should be established at this time, and the constructor should not pass the "instance of only a part of the example" to other methods.

Read "Effective Java Chinese" (15) Article 14: Compound priority to inheritance is a powerful means of implementing code reuse, but inhalation of inheritance can lead to fragile software.

Inheritance in a package is very secure, because the son class and super class are controlled by the same programmer. For classes designed for inheritance, use inheritance is also safe. It is very dangerous to inherit the boundary of the general specific class (CONCRET CLASS).

Unlike method calls, inheriting breaks encapsulation, a subclass depends on the implementation details of specific functions in its superclass. The subclass of changes can be broken.

Self-use, that is, when the implementation of different public methods in the superclass Remove these methods, abnormal data or operations. After the subclass inherits the superclass, it is possible to increase the problem when the superclass has increased the same prototype characteristics in the new version.

There is a way to avoid all of the above questions: New classes, not extending an existing class, but set a private domain, which references an instance of this existing class. This design is called "Composition". Each instance method in the new class can call the corresponding method in the existing class instance, and return it, that is, "Forwarding Method". Such classes are relatively firm, which does not rely on existing classes. An example of a class has put another class's implementation, then the former's class is called a wrapper class. See an example: // wrapper class - uses composition in place of inheritancepublic class InstrumentedSet implements Set {private final Set s; private int addCount = 0; public InstrumentedSet (Set s) {this.s = s;} public boolean add (Object o) {AddCount ; returnis scN (); public boolean addall (c) {addcount = C.Size (); returnisaddall (c);} public int getaddcount () {Return AddCount;} // Forwarding Methodspublic void clear () {s.cle ();} public boolean contacts ({return scontains (} public boolean iSempty () {Return S.Isempty (); public int size () {RETURN S.SIZE ();} .... public string toString () {Return S.toString ();}} In the above example, the InstrumentSet class is modified to the SET class, which increases the counting characteristics. Sometimes, the combination of composite and forwarding these two techniques is incorrectly cited as "delegation". From the perspective of technology, this is not a delegate unless the packaging object passes himself to a packaged object. There is little shortcoming in packaging classes. It should be noted that the packaging class is not suitable for use in a callback framework. In the callback frame, the object passes its own reference to other objects to call back, after it is packaged, it does not know the situation of the outside package, so it passes a reference to yourself (this) When it causes the problem of wraping the outer packaging object during the callback. This is called a Self issue. Inheritance is appropriate when only the subtype (subtype) "" Subtype "is truly superclad. That is, the relationship between "IS-A" is present. In the Java platform, there are also places in violation of this rule: such as stack is not vector, so it should not be extended; the property list is not a list, so Properties should not expand HashTable. When deciding to use composite or expand, you have to see an API of the class trying to extend the class. If you are willing to spread these defects into your own API, use inheritance, otherwise you can use a new API.

Read "Effective Java Chinese" (16) Article 15: Either designer for inheritance, and give the document description, or prohibit the inheritance of a class specifically designed to inherit and have a good document description, means:

The document of this class must accurately describe the impact of the impact of each method. This class must have a document to indicate the self-employment of its rewritable method: for each public or protected method or constructor, its documentation It must be indicated which rewritable methods it calls is to call in any order, and the result of each call affects the subsequent processing. A convention is if a method calls a rewritable method, then a description of these calls should be included at the end of its document comment. In order for programmers to write more effective subclasses without having to bear unnecessary pain, a class must provide appropriate hooks (hook) in some form, so that in such a form of its internal workflow It can be a well-selected protected method, but it is also rare to the protected domain. When designing a class that may be widely used in the purpose of inheritance, it must be aware that the self-use pattern described in the document, and the implementation implicitly imposed on the protected method and the domain Details, actually have made a permanent commitment. These commitments have made you improve this class in subsequent versions, or it is very difficult, or it is impossible. The constructor must not call the rewritable method, whether it is direct or indirect, because the superclass constructor runs before the constructor of the subclass. View example: public class super {// broken-constructor invokes overridable method public super () {m ();} distribLic void m ()};} final class sub extends super {private factory deflection; = new date ();} public void m () {system.out.println (date); public static void main (String [] args) {sub s = new sub (); SM ();}} program operation The result will not print the date twice, first play null. In a class designed to inherit, implement the cloneable or serializable interface, because the clone and readobject methods are very similar to constructor on the behavior, so regardless of clone or Does ReadObject cannot call a rewritable method, whether it is direct or indirect. For the ReadObject method, the method of rewrite the version in the subclass will be run before the subclass is too resembled. For the Clone method, the version of the method will have a chance to fix the status of the cloned object in the clonality of the Cloning object on the Clone method of the subclass. Before you have been run. In a class designed to inherit, the Serializable interface is implemented, and the class has a ReadResolve or WriteReplace method, you must make ReadResolve or WriteReplace a protected approach, not a private method. In order to inherit, a class is designed, requiring some substantial restrictions on this class. Subclasses are prohibited for classes (such as ordinary specific classes) for those who are not designed and written in order to safely perform subcategory. There are two ways to prohibit subclasses: Statement to FINAL to turn all constructor into private or packaged privacy, add some public static factories to replace the position of the constructor if they must inherit from such classes To ensure that this type will never call its rewritable method. Read "Effective Java Chinese" (17) Article 16: The interface is better than the interface between the abstract class Java language and the abstraction class:

The abstract class allows the implementation of certain methods, and the interface is not allowed. To implement a type defined by an abstract class, it must be a subclass of an abstract class. Any class, as long as it defines all required methods, and comply with the general agreement, it allows an interface to be implemented. Java only allows single inheritance, and abstract classes are greatly limited as type definitions. Look at the interface:

Some classes can be easily updated to implement new interfaces. As long as: increase the requirements of the requirements, add the imports clause from the statement of the class.

The interface is ideal for defining a Mixin (mixed type). A Mixin refers to this type: A class can implement this Mixin type in addition to its basic type (Primary Type) to indicate that it provides some optional behavior. The interface can define Mixin because it allows an optional function to be mixed into a type of basic type, and abstract classes cannot be used to define the Mixin type, because they cannot be updated to existing classes : A class is not likely to have more than one parent class, and there is no appropriate place in the class hierarchy to place Mixin. The interface allows us to construct a type structure of a non-hierarchical structure. View example: public interface singer {audioclip start (song s);} public interface songwriter {song compose (boolean hit);} To solve the singing home, you can do it, you can do it very simple: public interface SingersongWriter Extends Singer, Songwriter {Audioclip Strum (); void actSensitive ();} What will be made if you use an abstract class?

The interface makes it possible to securely enhance a class of functions, and the practice is the use of the package model described in Section 14. If you do with an abstract type, the programmer does not have other methods inherited inheritance.

The interface does not allow the implementation of the method. Combining the advantages of the interface and abstract classes, providing an abstract skeleton implementation (SkeleTal Implementaion) for each important interface desired to export. The role of the interface is still the definition type, and the skeleton implementation class is responsible for all work related to the interface. According to conventions, the skeleton implementation is called AbstractInterface (Note: This interface is the name of the interface implemented, such as AbstractList, AbstractSet). Look at a static factory: // list adapter for int ArrayStatic List INTARRAYASLIST (Final Int "{if (a == null) throw new nullpointRactList (); return new abstractList () {public object GET (INT i) {Return New Integer (a [i]); public int size () {return a.length;} public object set (int j = a [i]; a [i] = ((Integer) o) .intValue (); return new integer ();}}} This example is an Adapter, which makes an int array can be seen as an Integer instance list (due to the conversion between INT and Integer, its performance is not Will be very good) beautifully achieved beauty, they provide achievements for abstract classes, but there is no strict limitations that "abstract classes are used for type definition". For most implementations of one interface, the expansion of the skeleton implementation is an obvious choice, of course it is just a choice. A class that implements this interface can forward calls to the interface method to an instance of an internal private class, and this internal private class extends the skeleton implementation class. This technology is called analog multiple inheritance. Write a skeleton implementation class relatively simple, first carefully study the interface, and what is the most basic (Primitive), and other methods will be based on them, these methods will be the abstraction of the skeleton Methods; then provide specific implementation for other methods in the interface. The skeleton achievement is not designed for the purpose of inheritance. (How to understand?) See example: // skeletal importationpublic Abstract Class AbstractMapenTry Implements map.Entry {// primitiveSpublic Abstract Object getKey (); public Abstract Object getValue ();

// Entries in modifiable maps must override this methodpublic Object setValue (Object value) {throw new UnsupportedOperationException ();} // Implements the general contract of Map.Entry.equalspublic boolean equals (Object o) {if (o == this) Return True; if (! (o instanceof map.entry) Return False; map.entry arg = (map.entry) O; return EQ (getKey (), arg.getKey () && EQ (GetValue (), arg. getValue ());} Private Static Boolean EQ (Object O1, Object O2) {RETURN (O1 == NULL? 02 == NULL: O1.Equals (O2)); Hashcodepublic int 6code () {RETURN (getKey () == NULL? 0: getKey.hashcode ()) ^ (getValue () == NULL? 0: getValue (). hashcode ());}} Using an abstract class to define Allow multiple implementations, there is a significant advantage than the use interface: the evolution of abstract classes is much easier than the evolution of the interface. In subsequent releases, if you want to add a method in an abstract class, only one default reasonable implementation can, all implementations of the abstract class are automatically provided. For the interface, this is not good. Although the implementation of a method can be added in the skeleton implementation class to solve some problems, this cannot solve the problem of interface implementation without the inheritance of the skeleton. As a result, the design public interface should be very cautious, once an interface is disclosed and widely implemented, it will be impossible to modify it.

Read "Effective Java Chinese" (18) Section 17: The interface is just used to define the type When a class implements an interface, this interface is used to make a type (TYPE), which can reference this class. Example. Therefore, a class implements an interface that the customer can implement certain actions for instances of this class. The interface is not suitable for any other purpose.

The constant interface is a bad application of the interface because it does not satisfy the above conditions. There is no method in the constant interface, and only a static Final domain, each domain exports a constant. r Looks below. If a class wants to use these constants, it can avoid using class names to modify the constant name as long as you implement this interface. However, implementing a constant interface, which leads to this implementation detail (referred to internally using constants) to the exported API of this class. And in future release versions, if the class is no longer needed, this interface is still required. Also, the subclasses of such a class will also be contaminated with constants. // Constant interface pattern - do not use public interface PhysicalConstants {static final double AVOGADROS_NUMBER = 6.02214199e23; static final double BOLTZMANN_CONSTANT = 1.3806503e-23; static final double ELECTRON_MASS 9.10938188e-31;}!

There are several constant interfaces in the Java platform, such as Java.io.ObjectStreamConstants, which is not worthy. If you want to export constants, there are several scenarios: If this constant is tightly associated with an existing or interface, you should join the class or constant.

If these constants are best seen as a member of an enumeration type, you should use a TypeSafe Enum Class, see Article 21.

Otherwise, apply a tool class that cannot be instantiated, see Article 3. See modifications to the example above: // constant utility classpublic class PhysicalConstants {private PhysicalConstants () {}; // prevent instantiationpublic static final double AVOGADROS_NUMBER = 6.02214199e23; public static final double BOLTZMANN_CONSTANT = 1.3806503e-23; public static final double ELECTRON_MASS 9.10938188E-31;

You can reduce the entry workload of the keyboard by placing a constant in a local variable. Such as: private static final double pi = math.pi;

Read "Effective Java Chinese" (19) Article 18: Priority to the static member class nested (NESTED CLASS) refers to a class that is defined in another class, which is only for its peripheral services. If a nested class may be used for other an environment, it should be a top-level class. Nested classes have four: Static Member Class, Nonstatic Member Class, Anonymous Class, Local Class, which is called internal classes (Inner) Class).

Static member class is the simplest nested class, and finally seeing it as an ordinary class, happens to be declared in another class, it can access all members of the periphery, including those who state themselves . Static members are a static member of the peripheral, like other static members, comply with the same accessibility rules. If it is declared as private, you can only be accessed inside the periphery. A static member class is usually used as a public auxiliary class, which makes sense when it is used with its external classes. From the grammatical, the difference in non-static member classes and static member classes is that the latter has a Static. Each example of a non-static member class is implied with an peripheral instance of the periphery. Inside the example method of non-static members, the method of calling the peripheral example is possible, or using a modified THIS can also obtain a reference to the periphery instance. In the case where there is no peripheral example, it is impossible to create an instance of a non-static member class. One common use of non-static member classes is to define an Adapter that allows an instance of the external class to be regarded as an example of another unrelated class. For example, the implementation of the MAP interface often uses non-statistial members to implement their "collection" view, these "Collection" views are returned by the keyst, entryset, value method of the Map. Look Set collection interfaces example of an implementation iterator: // Typical use of a nonstatic member classpublic class MySet extends AbstractSet {// bulk of the class omittedpublic Iterator interator () {return new MyIterator ();} private class MyIterator implements Iterator { ...}} If the membership of the declaration does not require access to the peripheral instance, then the Static modifier is placed in a member of the member class. This reduces the overhead of the maintenance member class instance to the peripheral instance object. One of the usual use of private static members is to represent components of the peripheral objects. For example, the MAP instance associates some key and value, which typically has an ENTRY object corresponding to each key value pair. Each Entry object is associated with an MAP object, but both the method of entry (getKey, getValue, setvalue) does not require the peripheral MAP. At this point, it is the best choice with a private static member class. Anonymous class has no name, it is not a member of the periphery. It does not be declared along with other members, while notice and instantiating at the same point. Anonymous classes can appear in any place where the expression is allowed to appear in the code. The anonymous behavior is very similar to the member class, depending on its environment: if an anonymous class appears in a non-static environment, it has an peripheral instance. The applicability of anonymous classes has some restrictions: The anonymous class can only be used in the point in which it will be instantiated. It does not have a name. After instantiation, it cannot be referred to anonymous to refer to it. It usually only implements its interface or hyperclass, which does not declares a new method because there is no way to access new methods. Because anonymous classes appear in expression, they should be very short (20 rows or fewer) to enhance the readability of the program.

Common usage of anonymous classes:

One of an anonymous class is to create a function object, such as: // typical use of an anonymous class // arrays.sort (args, new compares () {public int compare (Object O1, Object O2) { Return (String) O1) .length () - ((String) O2) .length ();}});

Another common usage is to create a process object, such as Thread, Runnable, Timertasker instance.

Inside a static factory method (see Article 16) uses in complex type safety enumeration types (it requires separate subclasses for each instance): // Typical Use of a public static member classpublic class calculator { public static abstract class Operation {private final String name; Operation (String name) {this.name = name;} public String toString () {return this.name}; // perform arithmetic op represented by this constantabstract double eval (double x Double Y);

// Double Nested Anonymous ClassSpublic Static Final Operation Plus = New Operation (" ") {Double Eval (Double X, Double Y) {Return X Y;}} public static firm Operation minus = new operation ("-") { Double Eval (double x, double y) {return xy;}} public static final operation timees = new operation ("*") {double eval (double x, double y) {return x * y;}} public static firm Operation Divide = new operation ("/") {Double EVAL (Double X, Double Y) {Return X / Y;}}} // Return HTE Results Of The Specified CalculationPublic Double Calculate (Double X, Operation Op, Double Y) { Return Op.eval (x, y);}}

The local class is the least used in four nested classes. Partial class can be declared at any place where "can declare local variables". Like member classes, local classes have names and can be reused. As with an anonymous class, when and only the partial class is used in a non-static environment, they have peripheral instances. As with anonymous class, it must be non-simple to harm the peripheral method or the readability of the initializer. In summary, if a nested class is still visible outside of a single method, or it is too long, it is not suitable for placing inside a method, and a member class should be used. If each instance of the member class requires a reference to the instance of the periphery, the member class is not static; otherwise it is static. Suppose a nested class belongs to the inside of a method, if only one place is required to create its instance, and there is already a pre-existing type to explain the feature of this class, make it anonymous class; otherwise become part class.

Read "Effective Java Chinese" (20) Class 19: Use a class instead of the structure Java language to let a class degraded to only some public data domains, such as the structure of the C language similar, such as: // degenerate Classes Like this sales not be publicclass point {public float x; public float y;} This class has abandoned all data packages, and you can hardly do what changes or limitations on such APIs, should be in private domains and Public access method, such as: // Encapsulated structure classclass point {private float x; private float y; public point (float x, float y) {this.x = x; THIS.Y = Y;

Public float getx () {returnid gety () {returnid gety () {return this.y;} public void setx (float x) {this.x = x;} public void sety {THIS.Y = Y;}} Java platform library, there are several classes that violate the "public class should not directly expose the data field", such as Point and Dimension in Java.aw.

转载请注明原文地址:https://www.9cbs.com/read-106794.html

New Post(0)