Java interface and abstract class

Source: Internet
Author: User

In an object-oriented system, various functions of the system are completed by collaboration of many different objects. In this case, it is not that important for system designers to implement their own internal objects. The collaboration relationship 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, which is also 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 the consciousness in this aspect, you are only passively implementing this idea; it is manifested in frequent complaints that the Code modified by others has affected you (the interface is not designed), and the changes in a module have caused large-scale adjustments to other modules (the module interface is not well designed) 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 sum of the space and external influencing factors of the system elements. 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 any other interface, but in terms of understanding the UML interface, the implementation of each part of the system works 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. That is, Comrade billjoy said, turning the RFC and writing 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, people who know the abstraction understand 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, you should achieve this goal when designing the description of entity behavior: when using an entity, you do not need to know the implementation of entity 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 define methods that do not provide specific implementations, 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 feature can be defined either using an interface or using an abstract class. 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 the Java method. The Code is as follows:

Java code

  1. Public AbstractMotor {
  2. Abstract Public IntGethorsepower ();
  3. }
public abstract Motor{                     abstract public int getHorsepower();                  }

Based on the motor abstract class, a variety of specific implementations are constructed, such as A-type engine and B-type engine. In addition to other components of the system, software of version 1.0 is obtained and delivered for use. 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. The sales department 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: Java code

  1. Public AbstractBatterypoweredmotorExtendsMotor {
  2. Abstract Public IntGettimetorecharge ();
  3. }
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. After these changes were added to the 2.0 software, the sales department was satisfied. With the continuous development of business, light-driven engines emerged soon. The sales department requires that the light-driven engine must be able to run only a certain amount of energy, and the light energy should be 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 must add support for Optical-driven engines for 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:

Java code
  1. Public AbstractSolarpoweredmotorExtendsMotor {
  2. Abstract Public IntGetlumenstooperate ();
  3. }
public abstract SolarPoweredMotor extends Motor{                     abstract public int getLumensToOperate();                }

1. Both solarpoweredmotor and batterypoweredmotor are derived from the motor abstract class. More than 90% of the Code in the software 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:

Java code
  1. If(InstanceofSolarpoweredmotor ){...}
  2. If(InstanceofBatterypoweredmotor ){...}
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 behavior of the optical drive and the electric drive does not change, but the new engine supports both 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, there are no known bugs. To add a photoelectric drive engine, define a new abstract class of solarbatterypowered. If you want solarbatterypowered to be derived from the motor abstract class, solarbatterypowered does not support the instanceof operation for an optical and Electrical Drive engine. That is to say, if you query whether a photoelectric-driven engine is a light-driven or an electric-driven engine, the answer is: none.

If you want solarbatterypowered to be derived from the solarpoweredmotor (or batterypoweredmotor) abstract class, similar problems may occur. solarbatterypowered does not support instanceof operations on batterypoweredmotor (or solarpoweredmotor. In terms of behavior, the photoelectric-driven engine must be derived from two abstract classes at the same time, 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: Java code

  1. Public InterfaceMotor (){
  2. Public IntGethorsepower ();
  3. }
public interface Motor(){                  public int getHorsepower();                }

Behavior 2: Java code

  1. Public InterfaceBatterypoweredmotorExtendsMotor (){
  2. Public IntGettimetorecharge ();
  3. }
public interface BatteryPoweredMotor extends Motor(){             public int getTimeToRecharge();          }

Behavior 3: Java code

  1. Public InterfaceSolarpoweredmotorExtendsMotor {
  2. Abstract Public IntGetlumenstooperate ();
  3. }
public interface SolarPoweredMotor extends Motor{             abstract public int getLumensToOperate();          }

The photoelectric drive engine can be described as follows:

Java code
  1. PublicDualpoweredmotorImplementsSolarpoweredmotor, batterypoweredmotor {}
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, it 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 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 often leads to overly complex inheritance relationships, and defining behavior through interfaces can more effectively separate behavior and implementation, it facilitates 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.

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.