Java Programming thought Note 02: Combination and inheritance, final, policy design pattern and adapter pattern, inner class, serialization control (considerations)

Source: Internet
Author: User

1. Selection between combinations and inheritance

Both combination and inheritance allow child objects to be placed in a new class, and the combination is explicitly done, whereas inheritance is implicitly done.

Combinatorial techniques are typically used in situations where you want to use the functionality of an existing class in a new class rather than its interface. is to embed an object in the new class to implement the functionality that is required, but the new class's users see only the interface defined for the new class, not the interface of the embedded object. To achieve this effect, you need to embed a private object of an existing class in the new class. Sometimes, however, it is very meaningful to allow users of a class to access the composition components of a new class directly, declaring the member object as public. This is safe if the member object itself hides a specific implementation. When the user is able to understand that you are assembling a set of parts, it makes the port easier to understand. For example, a car object can be combined by a public engine object, a wheel object, a Window object, and a door object. But be sure to remember that this is only a special case, in general, the domain should be made private.

At the time of inheritance, use an existing class and develop a special version of it. Typically, this means that you are using a generic class and specialize it for a particular need. A little thought will reveal that it makes no sense to use a "vehicle" object to form a "car", because "the car" does not contain "transport", it is only a means of transport (is-a relationship).

The relationship of "is-a" (is a) is expressed by inheritance, while the relationship of "has-a" (one) is expressed by a combination.

In the end is the use of combination or inheritance, one of the clearest way to judge is to ask yourself whether you need to change from the new class to the base class, the need to use inheritance, do not need to use the combination.

2. Final keyword

Misconceptions about the final keyword

When the final decoration is a basic data type, it refers to a constant number of values (that is, compile-time constants, if the static final decoration, it is emphasized only one copy), and the object reference instead of the basic type of final, its meaning is a little confusing, because when used for object reference, Final makes the reference constant, and once the reference is initialized to an object, it can no longer be pointed to another object. However, the object itself can be modified, and Java does not provide a way to make any object constant (but you can write your own class to achieve a constant effect on the object), the same restriction applies to the array, it is also an object.

Can using the final method really improve program efficiency?

Once a method is set to final, the compiler can place all calls to that method into an "embedded" call. As soon as the compiler discovers a final method call, it ignores (according to its own judgment) the general code insertion method taken to execute the method invocation mechanism (the argument is pressed into the stack; jumps to the method code and executes it, jumps back, clears the stack argument, and finally processes the return value). Instead, it replaces the method call with a copy of the actual code within the method body. Doing so avoids the overhead of the method invocation. Of course, if the method size is too large, then the program will become more and more swollen, may be less than the embedded code to bring any performance improvement. Because any ascension is offset by the time spent inside the method.

In the recent Java release, virtual machines (especially hotspot technology) automatically detect these situations and, rather "wisely", decide whether to embed a final method. However, it is best not to fully believe that the compiler can make all the judgments correctly. Typically, you should consider setting a method to final only if the code for the method is very small, or if you want to explicitly prohibit the method from being overwritten.

All private methods within a class are automatically final. Since we cannot access a private method, it will never be overwritten by other methods (if forced to do so, the compiler will give an error). You can add a final indicator to a private method, but you cannot provide any additional meaning to that method.

3, the difference between the policy design mode and the adapter mode

Policy Design Patterns

Creating a method that behaves differently depending on the parameter object being passed is called the policy design pattern, which contains fixed portions of the algorithm to be executed, and "policy" contains the changed parts. A policy is a parameter object that is passed in, which contains the code to execute.

Adapter mode

When you can't modify the class you want to use, you can use the adapter mode, and the code in the adapter will accept the interface you have and produce the interface you need.

4. Inner class

It is important that internal classes and combinations are completely different concepts.

Why do I need an internal class? -mainly solves the problem of multiple inheritance, inheriting concrete or abstract classes

In general, an inner class inherits from a class or implements an interface, and the inner class's code action creates an object of its outer class. So it can be thought that the inner class provides some kind of window into its outer class.

The most appealing reason for inner classes is that each inner class inherits itself from the implementation of one (interface), so no matter whether the perimeter class has inherited an implementation of (an interface), there is no effect on the inner class.

Some design and programming problems can be difficult to solve without the ability of an inner class to inherit multiple concrete or abstract classes. From this point of view, the inner class makes the solution of multiple inheritance complete. The interface solves some of the problems, while the inner class effectively implements "multiple inheritance". That is, the inner class allows inheriting multiple non-interface types.

Consider a scenario where two interfaces must be implemented in a class in some way. Because of the flexibility of the interface, you have two choices: use a single class or use an inner class. But if you have an abstract class or a specific class, rather than an interface, you can only use inner classes to achieve multiple inheritance.

With internal classes, you can also get some additional features:

-----an inner class can have multiple instances, each with its own state information, and the information of its peripheral class objects is independent of each other.

-----in a single perimeter class, you can have multiple inner classes implement the same interface differently or inherit the same class.

-----creation of an inner class object does not depend on the creation of the perimeter class object.

-----Inner class does not have a confusing is-a relationship, it is a separate entity.

5. Serialization control

When we control serialization, it is possible that a particular sub-object does not want the Java serialization mechanism to be automatically saved and restored. This is usually the case if the child object represents sensitive information, such as a password, that we do not want to serialize. Even if the information in the object is a private property, once serialized, people can access it by reading the file or intercepting the transmission of the network. There are two ways to prevent the sensitive parts of an object from being serialized:

Implementing externalizable instead of implementing the Serializable interface to control the serialization process, Externalizable inherits the serializable interface and adds two methods: Writeexternal () and Readexternal ().

The difference between the two when deserializing:

----deserialization of a serializable object , because the serializable object is constructed entirely on the basis of its stored bits, no constructors are called. Therefore, the serializable class does not need a default constructor, but when the parent class of the Serializable class does not implement the Serializable interface, the deserialization process calls the parent class's default constructor, so the parent class must have a default constructor, or throw an exception.

----The externalizable object is deserialized , the class's constructor with no arguments is called first, which is different from the default deserialization method. If you delete a class's constructor without parameters, or set the access permission of the constructor to private, default, or protected level, the Java.io.InvalidException:no valid constructor exception is thrown. Therefore, the Externalizable object must have a default constructor and be public.

An alternative to----externalizable: If you do not insist on implementing the Externalizable interface in particular, there is another way. We can implement the serializable interface and add methods for WriteObject () and ReadObject (). Once the object is serialized or reassembled, the two methods are called separately. That is, as long as these two methods are provided, they are used preferentially, regardless of the default serialization mechanism.

These methods must contain the following exact signatures:

private void WriteObject (ObjectOutputStream stream)

Throws IOException;

private void ReadObject (ObjectInputStream stream)

Throws IOException, ClassNotFoundException

----can turn off serialization by field with the transient keyword, which means "don't bother you to save or recover data-I'll handle it myself." Because Externalizable objects do not save any of their fields by default, the Transient keyword can only be used with serializable objects.

6, summary :

On the end of the combination or inheritance, my understanding is that priority to use the combination, less inheritance, it is the inheritance of multiple direct classes, will make your program disastrous consequences; internal classes compensate for multiple inheritance problems and need to be aware of the life cycle of the external classes that depend on them. The Parcelable interface in Android provides a better performance for serialization.

Java Programming thought Note 02: Combination and inheritance, final, policy design pattern and adapter pattern, inner class, serialization control (considerations)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.