Basic Java series and interfaces

Source: Internet
Author: User

Personal nonsense

Class is the core concept of object-oriented. In my understanding, it is actually a kind of encapsulation of data structures and corresponding services, while object-oriented, in addition to the advanced object-oriented thinking, it also supports a series of related technologies related to classes, such as polymorphism. Why does Object-Oriented Programming become the mainstream programming? In my opinion, compared with data stream (process-oriented programming), object-oriented programming is more in line with human thinking habits and the nature of things. In addition, it is a powerful library. Of course, if the process-oriented language can also implement code reuse and API programming, but this implementation will seem a little confusing because it does not have encapsulation or other concepts. However, to provide these Object-oriented technologies, you have to pay the price-program efficiency. Because many technologies and features are supported, the efficiency cannot compete with the process-oriented language (especially the C language, to correctly understand the object-oriented and process-oriented technologies and adapt them to different fields, C and Java languages should be taken as representatives, C language is an appropriate choice for programs with high execution efficiency (such as OS, Web servers, databases, and embedded systems ), java is more suitable as a production language (Web development, desktop programs, and so on ). At these two levels, I love the conciseness, efficiency, and ability to describe data structures of C language, and I am persistent in Java's powerful API and production efficiency. When I use C language programming, most of the time I am paying attention to the details of data structures, data streams, and so on, which are not very relevant to actual transaction processing (although at the bottom of the transaction, I sometimes cannot grasp the overall programming task as a whole (I found that if the relevant APIs are designed at the beginning, many problems can be solved-top-down design ), when using Java, almost all transactions are being processed. For the underlying data structure, only efficient algorithms focus on details, this improves the efficiency of processing transactions by yourself (because others have already done a lot for me, in my opinion, it is a language that affects my life's programming ideas. PS: Sometimes I want to design a new programming language, which has both the underlying capabilities of C language and high-level abstract capabilities of Java (definitely not C ++, I do not really like C ++, at least C ++ in textbooks). Wow, it must be cool!

Class

Classes in Java are supported by class keywords. A public class name must be consistent with the file name. Otherwise, compilation errors may occur. the class file has the same name as the main class (naturally, the file name is the same ).

A class is a template for object creation. Another synonym for the class is "encapsulation", which combines the data structure with the corresponding service. This mechanism makes the vast majority of objects produced by classes more inclined to provide services (services are actually method calls). Because services are based on data structures, but during programming, when others want to obtain some services, they do not have much concern about the data structure and implementation of the Service Room. Without classes, you cannot do things. Therefore, the basic task of Java programming is to create various classes.

The creation of a class is generally a noun, and the attributes in the class are also some nouns in the class, and the corresponding verb forms a service. For example, after a Person class is designed, its attributes include name, sex, and age, and corresponding services include getting up, eating, learning, and sleeping.

Internal class

An internal class is a class created inside the class, which can be divided into three types:

1. Static/non-static member internal class

2. Non-static local internal class

3. Anonymous internal class

From the perspective of designing and Solving Programming Problems, internal classes are more perfect mechanisms for multi-inheritance. Because the internal class has all the properties of the class, it can implement the interface and inherit non-interface types. As a common member of the class, it can access the attributes and services of the peripheral class without any obstruction, most of the reasons for being an internal class are to help this class solve the problems that need to be solved. A specific class belongs to a peripheral class, so although it is a member, but there is no need to consider too many other things, such as inheritance.

Each type of internal class has its own characteristics and naturally has different uses. If you declare that the member class does not require access to the instance of the peripheral class, you must always put the static modifier in its declaration. If an internal class is visible outside a single method, or it is very long, it is not suitable to be placed inside the method, but should be used as a member class.

Keywords supported by internal classes:. this and. new. If you need to reference an external object, you can use the external class name followed by the dot and this. Obviously, this. this cannot be used for static methods or static classes (only internal classes (also called Nested classes. In addition, common internal classes do not allow static member variables and methods to be declared .. The new keyword is used to generate internal class objects through peripheral class objects. For relevant code reference instances, refer to the implementation of HashMap in Java collections.

An anonymous internal class is particularly useful in implementing event listeners.

Internal classes also generate independent. class files with their own special identifiers $.

Basically, the usage of internal classes can play a very clever Role in the design at some time. How to design internal classes is still an issue of experience, the combination of Java interfaces and internal classes solves the problems that can be solved by C ++ multi-inheritance. Compared with C ++'s multi-inheritance, Java interfaces are simple and easy to understand.

Class advanced

A term related to classes is called Information Hiding or encapsulation, which is one of the basic principles of software design, the biggest reason is that it can effectively remove the coupling relationship between modules of the system, so that these modules can be independently developed, tested, optimized, used, and modified. This modular independent parallel development greatly improves production efficiency. If a system is well divided into modules using object-oriented languages, both development efficiency and overall program robustness and maintainability will be improved, the Design of classes becomes the core of development.

Design principles:

1. Minimize the accessibility of classes and members

Once a class is designed, it is a public commitment to its users in many cases. The core data structure of the class should be hidden, prevent users from accidental damage, resulting in service errors and even program crashes. Except for the special cases of static final domains, common classes should not contain public domains. For some data that may be accessed by the outside world, use the access method instead of setting the domain to public. Sometimes you may feel troublesome, but it must be something worth doing.

2. Minimize Variability

When designing a class, most of the time it is a specific function class (not an inherited class), this class should be set to final class at this time, sometimes only one instance is required for a class. The Singleton mode should be used to design this class at this time.

Because classes are immutable, they cannot be inherited and thus may have some potential impact. The fields in these classes are also unchanged as much as possible. Because immutable domains are thread-safe in nature, the synchronization mechanism is not required. When designing classes that may have multiple threads simultaneously accessing, thread security is particularly important. For example, servlet classes are essentially a class designed to comply with the singleton mode, there is no public variable domain, so the thread does not need to spend time to consider how to ensure security.

To make the class more controllable and final, it is a good choice to use the static factory mode to replace the constructor and privatize the class constructor at the same time. The advantage of this method is that it may improve the static factory algorithm to increase the performance of this class in subsequent improvements. Another advantage is that when the requirements for classes change, you can directly reload the static method and modify the corresponding algorithm without creating a new constructor, the creation of objects in the static factory can add corresponding algorithms and processing in the method, which greatly improves the flexibility of object creation and class maintenance.

3 combination takes precedence over inheritance

Inheritance is one of the three Object-oriented technologies, but breaks the encapsulation of classes. Inheritance also has many shortcomings and troubles, such as 1. the change of the parent class may affect the child class. The more child classes affect the child classes, the more powerful the child classes affect. The design of the parent class must have enough vision and experience to design a good parent class. 2. After the Child class overrides the parent class method, the method to be rewritten may be invalid or even wrong because it is unclear about the internal method calling mechanism of the parent class. 3. Design defects of some methods of the parent class cannot be modified due to various reasons. After the subclass is inherited, it is likely that it will not be able to be resolved, so it will bear the risk of the parent class API defects. Among the six principles of object-oriented programming, the second is calledRys replacement principleIt is related to class inheritance.

For inheritance and combination, you only need to ask yourself: "Do subcategories need to be transformed upwards ?", In other words, inheritance is practical only when the parent class and its subclass have a "is-a" relationship. A more explicit point is that the class used for inheritance is quite easy to see that it is used for inheritance.

Compound is another method of reuse, which is more flexible. For example, the following example shows how many times the set has stored data?

Use inheritance

ImportJava. util. HashSet;

Public classSetExtendsTest ExtendsHashSet {

Private intI = 0;

Private static final long SerialVersionUID= 1L;

@ Override

Public booleanAdd (E e ){

I ++;

Returnsuper. Add (e );

}

Public intGetNumber (){

ReturnI;

}

}

This design does meet your requirements. You do not need to overwrite the addAll method, because it indirectly uses the add method. You can also use the following method:

Publicclass AnoterWay Extends ForwardingSet {

Private int countNumber = 0;

Public AnoterWay (Set S ){

Super (s );

}

@ Override

Public boolean add (E e ){

CountNumber ++;

Returnsuper. add (e );

}

Public int getNumebr (){

ReturncountNumber;

}

}

ClassForwardingSet Implements Set {

Private final Set S;

Public ForwardingSet (Set S ){

This. s = s;

}

@ Override

Public boolean removeIf (Predicate Filter ){

Returns. removeIf (filter );

}

@ Override

Public Stream Stream (){

Returns. stream ();

}

}

I didn't write all the methods here. The idea is to use a class to forward the operation request to the set and rewrite the add method at the same time. However, the set here is based on the class that implements the set interface, applicable to any class that implements the set interface. It is precisely because AnotherWay wraps the set operation, so it is called the package class, that is, the package mode in the design mode. This design is just an example. Here there may be an issue of over-design, but it is true that the add method is no longer dependent on a specific class, thus improving the flexibility and robustness of the program.

In general, composite is more advantageous than inheritance (of course, this is not to say that composite is better than inheritance. The specific problem is analyzed in detail)

4. Classes used for inheritance

The Design of classes specifically designed for inheritance is actually very difficult. As mentioned above, once a public class is published (especially for inherited classes ), its service is a commitment to others. If you need to design a class specifically for inheritance, you must consider it as much as possible. However, more and more restrictions are imposed on this class, which is unavoidable. for members and methods, you cannot expose too much or expose too little, and the logical relationships within the class will not change in the future. Because this class is used for inheritance, class documentation is very important (for program documentation there is a motto: A good API documentation should describe what a given method has done, rather than how it is done ). Another note for this inherited class is that you should not let the constructor call methods that may be overwritten.

PublicclassConstructorTest {

PublicConstructorTest (){

Test ();

}

Public voidTest (){

System.Out. Println ("");

}

}

ClassConstructExtendsConstructorTest {

@ Override

Public voidTest (){

System.Out. Println ("B ");

}

}

If you are a newConstruct object, the printed result is two B, which is already a very good result. Because of the Inheritance Method of creating an object, this causes the subclass object to be created later than the parent class object, but the subclass overwrites a method of the parent class. The constructor of the parent class calls this method because of its polymorphism, as a result, the parent class is called in the override method of the subclass, but the subclass has not yet completed object creation. Imagine if a member of the subclass is used in the rewrite method, in this case, it is very likely that this program will encounter an uncertain error.

On the other hand, it is necessary for classes whose design purpose is not to be inherited to prohibit quilt category!

Interface)

Java interfaces are a feature of Java's implementation of multi-inheritance. However, since interfaces do not provide any method implementation, therefore, there may be method code redundancy in the actual encoding process. The interface can inherit (that is, inheritance is more appropriate) Other interfaces (through the implements keyword ). The domain is public static final, and the method is public. Even if you do not declare it, it is the default.

There is such a sentence in Java programming ideology (also the core principle of the design model): "The first way to reuse code is that programmers follow the interface to write their own classes ", this is one of the principles of object-oriented programming -----Interface-oriented programming! Dependency inversion principle in Design Guidelines.

The specific definition of dependency inversion is:

1. High-level modules should not depend on low-level modules. Both of them should depend on abstraction.
2. abstraction should not depend on details, but on abstraction.

The details here refer to the specific implementation of classes, while abstraction is of course an abstract class or interface.

In the description of the dependency inversion principle, "it is called the sign of object-oriented design. It is not important to use the language to compile the program, if writing is to consider how to abstract programming rather than detailed programming, that is, the dependencies in the program are terminated in abstract classes or interfaces, that is, object-oriented programming, and vice versa, procedural programming ". In fact, in small projects, dependency inversion is not very obvious, but for a slightly larger project, more than three subsystems are involved, then, different subsystems are divided into different modules. As the internal modules of subsystems depend on each other, the mutual dependencies between subsystems are more complex, not to mention the dependency between classes in each module, when the demand changes (may be due to real demand changes, technical updates, or higher developer levels) if you want to modify the dependency (whether modification at the method level or modification at the class level), the larger the system is. If the design is poor, the maintenance costs will be higher than the development cost, there is such a famous saying in large projects that "design is more difficult than implementation! ".

Another principle of interface design is the "interface isolation principle", which is based on the principle of dependency inversion. If Class A is dependent on Class B through interface I, Class C is dependent on Class D through interface I. If interface I is not the smallest interface for Class A and Class B, then class B and class D must implement the methods they do not need.

In this case, the interface I should be separated into smaller interfaces, such <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "" alt = "\">

Thus, the basic principle of interface separation is followed: to create a single interface, do not create a large and bloated interface, refine the interface as much as possible, and minimize the number of methods in the interface. That is to say, we need to create a dedicated interface for each class, instead of trying to create a very large interface for all the classes dependent on it to call.

When using the interface isolation principle to restrict interfaces, pay attention to the following points:

    The interface should be as small as possible, but limited. Refining the interface can improve the flexibility of the program design. However, if it is too small, it will cause too many interfaces and complicate the design. So be sure to make it moderate.
  • To customize services for classes that depend on interfaces, only expose the methods required by the called class, and hide the methods that are not required by the called class. Only by providing customized services for a module can the minimum dependency be established.
  • Improve cohesion and reduce external interactions. Make the interface do the most things in the least way.

    Compared with the fourth point in the class design criterion, an interface is designed and released once it is implemented and must implement all the required methods in the interface, it is basically a permanent commitment. Therefore, we need to consider the interface design repeatedly. The level is limited, so we cannot go into a deeper level.

    For more detailed design art, refer to the books related to design patterns. interfaces in Java are the core of Java, But designing this path requires more experience, if this step is completed, it is basically at the architect level.

Related Article

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.