Java interfaces, interface-oriented programming, and when to use interfaces. Select Java interface or abstract class

Source: Internet
Author: User

What is API-oriented programming?[Author: umlchina post from: www.umlchina.com]
In an object-oriented system, various functions of the system are completed by collaboration of many different objects. In this case, how does each object implement itself?
Not that important. The collaboration between objects becomes the key to system design. Communication between different classes and interaction between modules should be considered at the beginning of system design.
The main work of system design. Interface-oriented programming I think it refers to programming according to this idea! In fact, in daily work, you have already programmed according to the interface, but if you do not have this awareness, then
You are only passively implementing this idea. It is manifested in frequent complaints that the code changed by others affects you (the interface is not designed ), this is manifested in the large-scale adjustment of other modules caused by changes to a module (the module interface is not very
Good design) and so on.

Mr. booch talked about interaction designer that day. It refers to people who do this kind of design, but with a higher level. I think this type of people in our software design team is one of the most lacking talents.
Non-interface programming? Is it a process-oriented programming idea?

1. Understanding about interfaces.
The deeper understanding of interfaces should be the separation of definitions (Norms, constraints) and implementations (the principle of separation of real names.
Generally, when implementing a system, we usually integrate the definition and implementation without separation. In my opinion, the most understandable system design specification should be the separation of all definitions and implementations, although this may be a little complicated for some situations in the system.
The interface itself reflects the abstract understanding of the system by the system designer.
There are two types of interfaces: the first class is the abstraction of an individual, which can correspond to an abstract class );
The second type is an abstraction of an individual, that is, an abstraction interface );
An individual may have multiple abstract faces.
There is a difference between an abstract body and an abstract surface.

 
2. Another factor that cannot be ignored when designing an interface is the context (Environment) of the interface. The viewpoint of system theory is that the environment is the space and external influence of the system elements.
The sum of factors. Any interface is generated in a certain environment. Therefore, the impact of environment definition and environment changes on interfaces cannot be ignored. From the original environment, all interfaces will lose their original meaning.

3. According to the component development model (3C), the three components complement each other, and each other is integrated.

Object-oriented means that when we consider the problem, we take the object as the unit and consider its attributes and methods.
Process orientation refers to the implementation of a specific process (transaction process) when we consider the problem.
Interface Design and non-interface design are aimed at reusing technology, which is not a problem with object-oriented (process ).

In my opinion, the interface mentioned in UML is another protocol. It does not refer to com interfaces, CORBA interfaces, Java interfaces, Delphi interfaces, man-machine interfaces, or Nic interfaces.

 
In specific implementation, the UML interface can be implemented as a language interface, an interface in a distributed object environment, or other
Interface, but in terms of understanding the UML interface, it refers to the implementation and implementation of each part of the system, and work together through the Protocol defined by the interface.

 
Therefore, in my opinion, interface-oriented programming is intended to be oriented to abstract protocol programming. The implementers must strictly follow the protocol to implement it. Bill
According to Comrade joy, he translated the RFC and wrote the meaning of the Code. Object-Oriented Programming refers to abstract-oriented and concrete-oriented. Abstract and concrete are the unity of contradictions. It is impossible to have only abstract without concrete. Generally Abstract
Everyone understands this truth. However, some people only know what it is, but do not know what it is.

Therefore, it is useless to implement only interfaces, or to implement interfaces without interfaces.

So it is still honestly object-oriented programming, protocol-oriented programming, or nothing, honestly programming.

But I hate to talk about such a term. Why do we talk about leader-oriented programming? User-oriented programming? Leaders and users are sometimes very BT, so we are oriented to BT programming?

Select Java interface or abstract class

Many people have wondered why interfaces instead of abstract classes must be used in some places, and abstract classes instead of interfaces must be used in other places? In other words, when considering the generalization of Java classes, many may hesitate between interfaces and abstract classes, or even choose either.

In fact, the choice of interfaces and abstract classes is not arbitrary.
To understand the selection principles of interfaces and abstract classes, there are two important concepts: object behavior and object implementation. If an entity can be implemented in multiple ways, this must be achieved when designing the description of entity behavior.
Example: when using an object, you do not need to know the implementation method of the object behavior in detail. That is to say, we need to separate the behavior of the object from the implementation of the object. Since Java interfaces and abstract classes can both be defined
We do not provide specific implementation methods. Should I use interfaces or abstract classes when separating object behavior and object implementation?

Create behavior models using abstract classes

The choice of interfaces and abstract classes must follow the principle that the behavior model should always be defined through interfaces rather than abstract classes. To illustrate the cause, we will try to create a behavior model through the abstract class to see what problems will occur.

Suppose you want to design a software for the sales department, which contains a motor entity. Obviously, it is impossible to describe all aspects of the engine in detail in the engine object. It is only possible to describe certain features that are important to the current software. As to which features of the engine are important, it is necessary to communicate with the user (Sales Department) to determine.

People in the sales department require each engine to have a parameter called horsepower. For them, this is the only parameter worth noting. Based on this judgment, the engine behavior can be defined as the following.

Behavior 1: query the engine's horsepower. The engine returns an integer representing the horsepower.

Although it is still unclear how the engine gets the horsepower parameter, it is certain that the engine must support this behavior, and this is the only behavior characteristic of all engines that deserves attention. This
Behavior features can be defined either using interfaces or using abstract classes. To illustrate possible problems with the definition of abstract classes, the following uses abstract classes to create an engine behavior model and describes Behavior 1 using Java methods,
The Code is as follows:


     
      public abstract Motor{
      
abstract public int getHorsepower();
}

A variety of concrete implementations are constructed based on the motor abstract class, such as A-type engine and B-type engine. In addition to other components of the system, the software version 1.0 is obtained and handed in
Payment. A period of time has passed. Now we need to design the 2.0 version of software. In the evaluation of Version 2.0 software requirements, it was found that a small part of the engine is battery-driven, and the battery requires a certain amount of charging time. Sales
The Department administrator wants to check the charging time on the computer. Define a new behavior according to this requirement, as shown in figure 1.

Behavior 2: query the charging time of an electric-drive engine. The engine returns an integer that represents the charging time.

Use the Java method to describe this behavior. The Code is as follows:


     
      public abstract BatteryPoweredMotor extends Motor{
      
abstract public int getTimeToRecharge();
}

In the software of the sales department, electric-driven engines are also implemented in the form of classes, but these classes are derived from batterypoweredmotor rather than motor. These
After the change was added to version 2.0, the sales department was satisfied. With the continuous development of business, light-driven engines emerged soon. The sales department requires that only light-driven engines can be operated.
Measured by lumen. This information is important to customers because some light-driven engines may not work in rainy or cloudy weather. The sales department requires additional support for Optical-driven engines for the software.
So define a new behavior.

Behavior 3: query the minimum lumen number required for the optical drive engine to run properly. The engine returns an integer.

Define an abstract class and convert behavior 3 to a Java method. The Code is as follows:


     
      public abstract SolarPoweredMotor extends Motor{
      
abstract public int getLumensToOperate();
}

1. Both solarpoweredmotor and batterypoweredmotor are derived from the motor abstract class. In the entire software
In, more than 90% of the Code treats all engines in the same way. Occasionally, you need to check whether the engine is an optical drive or an electric drive. The Code is as follows:


     
      if (instanceof SolarPoweredMotor){...} 
      
if (instanceof BatteryPoweredMotor){...}

Regardless of the engine, the horsepower parameter is very important, so the gethorsepower () method works in all derived abstract classes (solarpoweredmotor and batterypoweredmotor.

Now the sales department has a new engine, which is a dual-drive engine with both electric and light drives. The light-driven and electric-driven behaviors have not changed, but the new launch
The host supports two actions at the same time. When considering how to define a new type of photoelectric drive engine, the difference between the interface and the abstract class begins to show. The new goal is to minimize code changes when new engines are added. Because
Code related to light-driven and electric-driven engines has been fully tested, and no known bugs exist. To add a photoelectric drive engine, define a new
Solarbatterypowered abstract class. If you want solarbatterypowered to be derived from the motor abstract class,
Solarbatterypowered will not support instanceof operations for light-driven and electric-driven engines. That is to say, if a photoelectric-driven engine is queried
The answer is: none.

If you want solarbatterypowered from solarpoweredmotor (or
Batterypoweredmotor) is derived from an abstract class. Similar problems may occur. solarbatterypowered does not support
Instanceof operation of batterypoweredmotor (or solarpoweredmotor. In terms of behavior, the photoelectric-driven engine must start from
The two abstract classes are derived, but the Java language does not allow multiple inheritance. The root cause of this problem is that using abstract classes not only defines specific behaviors, but also defines implementation patterns.
That is to say, we should define a model of how an engine obtains its behavior, not just declaring that an engine has a certain behavior.

Establish behavior models through interfaces

If you use interfaces to create a behavior model, you can avoid implicitly specifying the implementation mode. For example, the previous several actions are defined as follows using interfaces.

Behavior 1:


     
      public interface Motor(){
      
public int getHorsepower();
}

Behavior 2:


     
      public interface BatteryPoweredMotor extends Motor(){
      
public int getTimeToRecharge();
}

Behavior 3:


     
      public interface SolarPoweredMotor extends Motor{
      
abstract public int getLumensToOperate();
}

The photoelectric drive engine can be described as follows:


     
      public DualPoweredMotor implements SolarPoweredMotor, BatteryPoweredMotor{}
     

Dualpoweredmotor only inherits the behavior definition, rather than the implementation mode of the behavior, as shown in figure 2.

Abstract classes can still be used while using interfaces. However, abstract classes are used to implement behaviors rather than define behaviors. As long as the class implementing the behavior complies with the interface definition, even if it changes
The parent abstract class does not need to change the way other code interacts with it. Abstract classes have their advantages, especially for public implementation code. Abstract classes can ensure implementation hierarchies and avoid code duplication. However, even if
When using abstract classes, do not ignore the principle of defining behavior models through interfaces. From a practical point of view, if you rely on abstract classes to define behavior, it will often lead to overly complex inheritance relationships, and through the interface
Malicious behaviors can more effectively separate behavior and implementation, and facilitate code maintenance and modification.

Java interface feature learning

When you see the interface in Java, the first thought may be the multi-inheritance in C ++ and another keyword abstract in Java. Implementing Multi-inheritance from another perspective is one of the functions of interfaces. The existence of interfaces allows the objects in Java to be transformed to multiple base types, similar to the abstract class, this class object cannot be created by others because the interface does not allow object creation.

The interface keyword is used to declare an interface. It can generate a completely abstract class without any specific implementation. The interface features are as follows:

1. Methods in the interface can have parameter lists and return types, but cannot have any method bodies.

2. The interface can contain fields, but is implicitly declared as static and final.

3. The fields in the interface are only stored in the static storage area of the interface, not the interface.

4. Methods in the interface can be declared as public or not, but the results will be processed according to the Public type.

5. When implementing an interface, you must declare the defined method as public. Otherwise, it is the default access type, which is not allowed by the Java compiler.

6. If all methods in the interface are not implemented, an interface is created.

7. Extend an interface to generate a new interface using the keyword extends to implement an interface using implements.

 

Interface is similar to abstract in some places, but the following two methods are used to declare a class:

1. If you want to create a base class without any method definition or member variables, you should select an interface instead of an abstract class.

2. if you know that a class should be a base class, the first choice should be to make it an interface. The abstract class should be selected only when there must be a legal or member variable. Because one or more methods can be implemented in an abstract class, the class is still an abstract class as long as the methods are not fully implemented.

These are the basic features and application fields of interfaces, but they are not the same. In the Java syntax structure, interfaces can be nested and can be nested by a class, it can also be nested by interfaces. This may not be used much in actual development, but it is also one of its features. Note that when implementing an interface, you do not need to implement any interfaces nested inside it. Moreover, private interfaces cannot be implemented outside the class that defines it.

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.