Difference between abstract class and interface


I. Introduction

        This article is mainly composed of some personal opinions and information collected on the Internet. For programmers who use object-oriented programming languages, the term "interface" must be familiar, but I don't know if you have such doubts: what is the purpose of the interface? What's the difference between it and an abstract class? Can abstract classes be used instead of interfaces? Moreover, as a programmer, you must often hear the phrase "interface-oriented programming". What does it mean and what are the ideological connotations? What does it have to do with object-oriented programming? This article will answer these questions one by one.

Second, what is the relationship between interface-oriented programming and object-oriented programming

        First of all, interface-oriented programming and object-oriented programming are not equal. It is not an independent programming idea more advanced than object-oriented programming, but is attached to the object-oriented thinking system and belongs to it. In other words, it is one of the quintessence of the object-oriented programming system.

3. The essence of the interface

An interface, on the surface, is a collection of method definitions with no body code, a unique name, and can be implemented (or inherited) by a class or other interface. It might look like this in form:

public interface InterfaceName  
{  
    void Method1();  
    void Method2(int para1);  
    void Method3(String para2,String para3);  
}

So, what is the essence of an interface? Or what is the meaning of the existence of the interface. I think it can be considered from the following two perspectives:

1) An interface is a set of rules that specify a set of rules that a class or interface that implements this interface must have. Embodies nature's philosophy of "if you are... you must be able to...".

         For example, in nature, people can eat, that is, "if you are human, you must be able to eat". Then to simulate into a computer program, there should be an IPerson (customarily, the interface name starts with "I") interface, and there is a method called Eat(), and then we stipulate that each class representing "person" must implement IPerson interface, which simulates the rule of nature "if you are human, you must be able to eat".
         From here, I think you can also see a little bit of object-oriented thinking. One of the cores of object-oriented thinking is to simulate the real world, abstract things in the real world into classes, and the entire program relies on instances of each class to communicate with each other and cooperate with each other to complete system functions, which is very consistent with the real world. The essence of object thought.

2) An interface is an abstract representation of similar things on a certain granular view. Note that I have emphasized a certain granularity view here, because the concept of "like things" is relative, and it is different because of different granularity views.

        For example, in my eyes, I am a human being, and I am fundamentally different from a pig. I can accept the statement that I and my classmates are the same, but I must not accept that I am the same as a pig. However, if in the eyes of a zoologist, pigs and I should be of the same kind, because we are both animals, he can think that both "people" and "pigs" implement the IAnimal interface, but when he studies animal behavior, he does not He will treat me and pigs separately, and will study from the larger granularity of "animal", but he will think that there is an essential difference between me and a tree.
        Now I have changed to a geneticist, and the situation is different, because all living things can inherit, so in his eyes, I am not only the same as a pig, but also a mosquito, a bacterium, a tree, a mushroom and even a SARS virus There is no difference, because he will think that we all implement the interface IDescendable (Note: descend vi. Inheritance), that is, we are all heritable things, he will not study us separately, but will study all creatures as the same kind, In his eyes, there is no distinction between humans and viruses, only heritable substances and non-heritable substances. But at least, there is still a difference between me and a stone. But an unfortunate thing happened. One day, a great man appeared on the earth. His name was Lenin. Definition: The so-called matter is the objective reality that can be reflected by consciousness. So far, there is no difference between me and a stone, a trace of air, an idiom, and an electromagnetic field that transmits cell phone signals, because in Lenin's eyes, we are all objective reality that can be reflected by consciousness. If Lenin were a programmer, he would say this: The so-called substances are the instances generated by all classes that implement both the "IReflectabe" and "IEsse" interfaces.
        You might think my example above seems like a hoot, but that's exactly what interfaces are for. One of the object-oriented ideas and cores is called polymorphism. What is polymorphism? To put it bluntly, it is to treat similar things indiscriminately and uniformly at a granular view level. And the reason why I dare to do this is because of the existence of the interface. Like the geneticist, he understands that all organisms implement the IDescendable interface, so as long as they are organisms, there must be a Descend() method, so he can study them in a unified way, instead of studying each organism separately and eventually exhausted.
         It may not be possible to give you an intuitive impression of the nature and function of the interface here. Then in the following examples and analysis of several design patterns, you will experience the connotation of the interface more intuitively.

4. Overview of Interface-Oriented Programming

          Through the above, I think everyone has an understanding of the ideological connotation of interfaces and interfaces, so what is interface-oriented programming? My personal definition is: in system analysis and architecture, distinguish between layers and dependencies. Each layer does not directly provide services to its upper layer (that is, it is not directly instantiated in the upper layer), but only by defining a set of interfaces. The layer exposes its interface functions, and the upper layer only depends on the interface for the lower layer, not on specific classes.
        The benefits of doing so are obvious, first and foremost for system flexibility. When the lower layer needs to be changed, as long as the interface and interface functions remain unchanged, the upper layer does not need to make any changes. You can even replace the entire lower layer without changing the upper layer code, just like we replaced a WD 60G hard drive with a Seagate 160G hard drive. No changes are required in other parts of the computer, but the original hard drive is pulled out and the new hard drive is replaced. Just plug it in, because other parts of the computer do not depend on the specific hard disk, but only rely on an IDE interface. As long as the hard disk implements this interface, it can be replaced. From this point of view, the interface in the program is very similar to the interface in reality, so I always think that the word interface is really similar! Another advantage of using interfaces is that developers of different components or levels can start work in parallel, just like those who build hard drives do not need to wait for CPUs, nor do they need to wait for displays, as long as the interfaces are consistent and the design is reasonable, they can be developed in parallel, thus Improve efficiency.
        This article is here first. Finally, I would like to reiterate: the essence of object-oriented is to simulate reality, which can also be said to be the soul of my article. Therefore, thinking more about object-oriented things from reality is of great benefit to improving the ability of system analysis and design .

5. Supplement to this article

  • About the "interface" in "interface-oriented programming" and the two words "interface" in specific object-oriented languages

I saw a friend who proposed that the word "interface" in "interface-oriented programming" should have a wider scope than the interface in a simple programming language. After thinking about it, I think it makes sense. What I wrote here is really unreasonable. I think, "interface" in object-oriented languages ​​refers to a specific code structure, such as the interface defined with the interface keyword in C#. The "interface" in "interface-oriented programming" can be said to be a structural component used to hide specific underlying classes and implement polymorphism from the perspective of software architecture and from a more abstract level. In this sense, if an abstract class is defined, and the purpose is to achieve polymorphism, then I think it is reasonable to call this abstract class an "interface" as well. But is it reasonable to implement polymorphism with abstract classes? Discussed in Article 2 below. In general, I feel that the two concepts of "interface" are both distinct and interrelated. The interface in " interface-oriented programming" is an architectural component used to realize polymorphism and improve software flexibility and maintainability at the ideological level, while the "interface" in a specific language is a specific component in this idea. means .

  • About abstract classes and interfaces
     From the perspective of specific code, it is easy to blur these two concepts, and even think that the interface is redundant, because from the perspective of specific functions, except for multiple inheritance (C#, Java), abstract classes seem to be able to completely replace interfaces. . However, does the interface exist to achieve multiple inheritance? of course not. In my opinion, the difference between an abstract class and an interface is the motivation to use it. Abstract classes are used for code reuse, while interfaces are motivated for polymorphism . So, if you're hesitating about whether to use an interface or an abstract class somewhere, think about your motivation.
        Seeing some friends questioning the IPerson interface, my personal understanding is that whether the IPerson interface should be defined or not depends on the situation in the specific application. If there are Women and Man in our project, both of which inherit Person, and most of the methods of Women and Man are the same, only one method, DoSomethingInWC(), is different (the example is vulgar, please forgive me), then of course it is more reasonable to define an AbstractPerson abstract class , because it can include all other methods, the subclass only defines DoSomethingInWC(), which greatly reduces the amount of repetitive code. However, if the Women and Man classes in our program have basically no common code, and there is a PersonHandle class that needs to instantiate them, and do not want to know whether they are male or female, just treat them as people, and implement Polymorphism, then it is necessary to define it as an interface.
         All in all, an interface differs from an abstract class mainly in the motivation for its use, not in itself. Whether a thing should be defined as an abstract class or an interface depends on the context of the specific environment. Also, I think another difference between an interface and an abstract class is that there should be a general and special relationship between an abstract class and its subclasses, whereas an interface is just a set of rules that its subclasses should implement. (Of course, sometimes there may be general and special relationships, but the purpose of using interfaces is not here.) For example, it is acceptable to define vehicles as abstract classes, and cars, airplanes, and ships as subclasses, because cars, airplanes, etc. , ships are a special means of transportation. Another example is the Icomparable interface. It just says that the classes that implement this interface must be comparable. This is a rule. If the class Car implements Icomparable, it just means that we have a method in our Car that can compare two instances of Car, which might be more expensive or which might be bigger, it doesn't matter, But we can't say "the car is a special kind of comparable", it doesn't make sense grammatically.

6. Examples of application scenarios using abstract classes and interfaces

abstract class

People who have studied java have more or less knowledge of Android, so here are a few examples commonly used in Android.

ListView in Android is one of the most commonly used components for development. We often use custom Adapters to achieve our goals. Therefore, it is very common to write our own BaseAdapter, and the purpose of rewriting BaseAdapter is to write less repetitive code. And implement the getview() function you want, here we look at this abstract class:

package com.winton.basemodule;  
  
import java.util.List;  
  
import android.content.Context;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.BaseAdapter;  
  
public abstract class NewBaseAdapter<T> extends BaseAdapter {  
  
    public List<T> sourceList;  
    public LayoutInflater inflater;  
    public Context mContext;  
      
    public NewBaseAdapter(List<T> list ,Context context) {  
        // TODO Auto-generated constructor stub  
        sourceList=list;  
        mContext=context;  
        inflater=LayoutInflater.from(context);  
    }  
      
    public void updateListData(List<T> list){  
        sourceList=list;  
        notifyDataSetChanged();  
    }  
    @Override  
    public int getCount() {  
        // TODO Auto-generated method stub  
        return sourceList==null?0:sourceList.size();  
    }  
  
    @Override  
    public Object getItem(int position) {  
        // TODO Auto-generated method stub  
        return sourceList.get(position);  
    }  
  
    @Override  
    public long getItemId(int position) {  
        // TODO Auto-generated method stub  
        return position;  
    }  
  
    @Override  
    abstract public View getView(int position, View convertView, ViewGroup parent);  
      
}  
Let's look at the interface again. The purpose of the interface is to allow the objects that implement the interface to implement the same method in different ways, not to reduce repetitive code. Here is a Cache code. This interface formulates the rules for caching objects, that is, to achieve The cached object must implement the methods defined in the interface, so as to ensure the integrity of the cache function:
package com.android.volley;  
  
import java.util.Collections;  
import java.util.Map;  
  
/** 
 * An interface for a cache keyed by a String with a byte array as data. 
 */  
public interface Cache {  
    /** 
     * Retrieves an entry from the cache. 
     * aramparam key Cache key 
     * @return An {@link Entry} or null in the event of a cache miss 
     */  
    public Entry get(String key);  
  
    /** 
     * Adds or replaces an entry to the cache. 
     * aramparam key Cache key 
     * @param entry Data to store and metadata for cache coherency, TTL, etc. 
     */  
    public void put(String key, Entry entry);  
  
    /** 
     * Performs any potentially long-running actions needed to initialize the cache; 
     * will be called from a worker thread. 
     */  
    public void initialize();  
  
    /** 
     * Invalidates an entry in the cache. 
     * aramparam key Cache key 
     * @param fullExpire True to fully expire the entry, false to soft expire 
     */  
    public void invalidate(String key, boolean fullExpire);  
  
    /** 
     * Removes an entry from the cache. 
     * aramparam key Cache key 
     */  
    public void remove(String key);  
  
    /** 
     * Empties the cache. 
     */  
    public void clear();  
  
    /** 
     * Data and metadata for an entry returned by the cache. 
     */  
    public static class Entry {  
        /** The data returned from cache. */  
        public byte[] data;  
  
        /** ETag for cache coherency. */  
        public String etag;  
  
        /** Date of this response as reported by the server. */  
        public long serverDate;  
  
        /** The last modified date for the requested object. */  
        public long lastModified;  
  
        /** TTL for this record. */  
        public long ttl;  
  
        /** Soft TTL for this record. */  
        public long softTtl;  
  
        /** Immutable response headers as received from server; must be non-null. */  
        public Map<String, String> responseHeaders = Collections.emptyMap();  
  
        /** True if the entry is expired. */  
        public boolean isExpired() {  
            return this.ttl < System.currentTimeMillis();  
        }  
  
        /** True if a refresh is needed from the original data source. */  
        public boolean refreshNeeded() {  
            return this.softTtl < System.currentTimeMillis();  
        }  
    }  
  
}  

Reprinted: https://blog.csdn.net/wenwen091100304/article/details/48381023
Supplement: https://blog.csdn.net/cnuserfdg/article/details/51761816
          https://blog.csdn.net/qq_29344757/article/details/77346934

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325684070&siteId=291194637