Summary of usage examples of Java interfaces and abstract classes

  • 2020-04-01 04:33:04
  • OfStack

This article illustrates the use of Java interfaces and abstract classes. Share with you for your reference, as follows:

interface

1 because Java does not support multiple inheritance, so there is an interface, a class can only inherit one parent class, but you can implement multiple interfaces, the interface itself can also inherit multiple interfaces.

2. The member variables in the interface are of public static final type by default. Initialization that must be displayed.

Methods in the interface are of public abstract type by default. Implicit declaration.

The interface has no constructor and cannot be instantiated.

An interface cannot implement another interface, but it can inherit from multiple interfaces.

Class 6 if an interface is implemented, all the abstract methods in the interface must be implemented, otherwise the class is defined as an abstract class.

An abstract class

If you declare a class as abstract, this class cannot generate objects and can only be used by inheritance.

2   Abstract methods must exist in abstract classes.

3   Abstract classes can have generic variables and generic methods.

Subclasses that inherit from abstract classes must implement the abstract methods in them, unless subclasses are abstract classes.
    Private void print () {}; This statement represents an empty implementation of the method.
    The abstract void print (); This statement represents an abstraction of a method and has no implementation.

The difference between an interface and an abstract class

Interfaces can only contain abstract methods, and abstract classes can contain ordinary methods.
Interfaces can only define static constant properties. Abstract classes can define both normal and static constant properties.
Interfaces do not contain constructors, and abstract classes can contain constructors.        

Abstract classes can't be instantiated, but that doesn't mean they can't have constructors

The interface is the core, which defines what to do and contains many methods, but does not define how these methods should do it.
If many classes implement an interface, each of them implements those methods in code
3. If some class implementations have something in common, an abstract class can be abstracted so that the abstract class can implement the common code of the interface, while those personalized methods are implemented by each subclass.

So, abstract classes are designed to simplify the implementation of interfaces. They not only provide implementations of public methods that you can develop quickly, but also allow your classes to implement all the methods themselves without tight coupling.

The application is simple
Define the interface first
If you have multiple interface implementations that have a common part, use an abstract class and then integrate it.

The difference between an interface and an abstract class -- you won't be confused by it

I think, for you who use object-oriented programming languages, the term "interface" must be familiar, but I wonder if you have such doubts: what is the purpose of the interface? How is it different from an abstract class? Can you use abstract classes instead of interfaces? Also, as a programmer, you must often hear the phrase "programming to an interface", so what does it mean? What are the ideological implications? What is the relationship to object-oriented programming? This article will answer these questions one by one.

1. What is the relationship between interface-oriented programming and object-oriented programming

First of all, interface oriented programming and object oriented programming are not parallel, it is not more advanced than object oriented programming an independent programming thought, but is attached to the object oriented ideological system, is a part of it. In other words, it is one of the quintessential ideas in the object-oriented programming system.

2. The nature of interface

An interface, ostensibly a collection of several method definitions with no body code, has a unique name and can be implemented (or inherited) by a class or other interface. It may formally look like the following:


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

So what is the nature of an interface? Or what is the point of an 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 the class or interface that implements the interface must have. Embodies the nature of "if you are... Must be able to..." The idea of.

For example, in nature, people can eat, that is, "if you are human, you must be able to eat." So if you simulate it to a computer program, you should have an IPerson interface, and you should have a method called Eat(), and then we stipulate that every class that represents a "person" must implement the IPerson interface, which simulates the natural "if you are a person, you must be able to Eat" rule.

From here, I think you can see a little bit of object-oriented thinking as well. One of the core of object-oriented thought is to simulate the real world, to abstract the things in the real world into classes, the whole program relies on the instance of each class to communicate with each other, cooperate with each other to complete the system function, which is very consistent with the running condition of the real world, is also the essence of object-oriented thought.

2) an interface is an abstract representation of the same thing on a granular-grained view. Notice that I've emphasized here that at a certain granularity view, because the concept of "like thing" is relative, it varies depending on the granularity view.

For example, in my eyes, I am a person, and a pig is fundamentally different, I can accept that I and my classmates are the same species, but can never accept that I and a pig is the same species. But if, in the eyes of a zoologist, pig and I should be the same, because we are animals, he may think that "person" and "pig" are implemented IAnimal this interface, while he was in studies of animal behavior, not treat pigs and I separated, and from the larger granularity research "animals", but he will think that there is essential difference between I and a tree.

Now in a geneticist, and different, because the creatures can be genetic, so in his eyes, I not only and pig no difference, and a mosquito, a bacterium, a tree, a mushroom and a SARS virus has much difference, because he will think we are all realized IDescendable this interface (note: descend vi. Genetic), namely we are heritable things, he will not study we respectively, and all living creatures as a similar study, no and the points of the virus in his eyes, only can genetic material and genetic material. But at least there's a difference between me and a rock.

Unfortunately, one day, a great man appeared on the earth. His name was Lenin. After reading MAX and Engels' great works of dialectical materialism, he had a lot of insight. At this point, I am no more than a stone, a breath of air, an idiom, or the electromagnetic field that transmits mobile phone signals, because in Lenin's eyes, we are all objective realities that can be reflected by consciousness. If Lenin had been a programmer, he would have said that matter is an instance generated by all classes that implement both IReflectabe and IEsse interfaces. ) reflect, reflect, reflect, reflect Esse n.)

You might think my example above is a bit of a drivel, but that's what interfaces are for. One of the core of object-oriented thinking and thinking is called polymorphism. What is polymorphism? To put it simply is to treat the same kind of things in the same way without distinction at the level of a granular view. And dare to do so, because there is the existence of interface. Like the geneticist, he knew that all living things implement the IDescendable interface, and that as long as they are living things, there must be a trail of humanity, so he could study them all without trying to study each one and dying.

Maybe this doesn't give you an intuition of the nature and function of the interface. In the following examples and the analysis of several design patterns, you will get a more intuitive experience of what interfaces are all about.

3. Overview of interface oriented programming

Through the above, I want you to have an understanding of the interface and the concept of interface, so what is interface oriented programming? My personal definition is: in system analysis and architecture, distinguish between hierarchy and dependency, each layer is not directly to its layer provides services (i.e., not directly instantiated) in the upper, but by defining a set of interfaces, only to the upper exposed its interface function, upper to the lower interface is only rely on, and not rely on a concrete class.

The benefits of doing this are obvious, starting with the benefits to system flexibility. When the lower layer needs to be changed, the upper layer does not need to be changed as long as the interface and interface functions remain unchanged. Even can not change the upper code will lower the replace, as we will be a WD 60 gb hard drive for a Seagate 160 gb hard drive, computer without doing any changes in other places, but the original hard disk pull down, the new hard disk on line, because other parts of the computer does not depend on the specific hard drive, but only rely on an IDE interface, as long as the hard disk implements this interface, you can replace it. From this point of view, the interface in the program is very similar to the interface in the real world, so I have always thought that the word "interface" is really similar!

Another advantage of using interfaces is that developers at different parts or levels can work in parallel, just like those who build hard disks don't have to wait for cpus or monitors. As long as the interfaces are consistent and well-designed, they can be developed in parallel to improve efficiency.

So much for this article. Finally, I would like to add that the essence of object orientation is to simulate reality, which is the soul of my article. Therefore, it is beneficial to improve the ability of system analysis and design to think more about object oriented things in reality.

In the next article, I'll show you the basics of interface programming with an example.

In the third installment, I'll examine some of the ideas of interface-oriented programming in classic design patterns and the ideas of interface-oriented programming in the layered architecture of.net.

Supplement to this article:

I have read your reply carefully. I am very glad to discuss the technical problem with you. Thanks to the friends who give affirmation, but also thanks to the friends who raise opinions and questions, this made me think more deeply about something, hoping to make progress. I would like to add something here to discuss some of the more focused issues in the responses.

1. About "interface" in "interface oriented programming" and "interface" in specific object-oriented language

I have seen some friends suggest that the word "interface" in "interface oriented programming" should have a wider range than interface in a pure programming language. I think it makes sense. I'm not really making sense here. I think an "interface" in an object-oriented language is a specific code structure, such as an interface defined in C# with the interface keyword. And the "interface" in "interface oriented programming" can be said to be a kind of structural parts used to hide the concrete underlying classes and realize polymorphism from the perspective of software architecture at a more abstract level. In this sense, if you define an abstract class and the purpose is to achieve polymorphism, then I think it makes sense to also call that abstract class an "interface." But does it make sense to implement polymorphism with abstract classes? This is discussed in the second section below.

Generally speaking, I think the two concepts of "interface" are both different and related to each other. An interface in "interface-oriented programming" is an architectural piece of thought for polymorphism, software flexibility, and maintainability, and a language-specific "interface" is a way to implement that piece of thought into code.

2. About abstract classes and interfaces

I saw in the reply that this was a heated discussion. I'm sorry I didn't think it through and didn't discuss it in the article. My personal understanding of this issue is as follows:

It's easy to blur these two concepts and even think of an interface as redundant if you just look at the code, because the abstract class seems to completely replace the interface except for multiple inheritance (C#, in Java). But do interfaces exist to implement multiple inheritance? Of course not. In my opinion, the difference between an abstract class and an interface is the use motivation. Abstract classes are used for code reuse, and interfaces are motivated for polymorphism. So, if you're hesitating between using an interface or an abstract class somewhere, think about your motivation.

I have seen some friends' doubts about the interface of IPerson. My personal understanding is that whether the interface of IPerson should be defined or not depends on the specific situation in the application. If there is "Women and Man in our project, inherit the Person, and" Women and Man most of the methods are the same, is only one way DoSomethingInWC () different (example is vulgar, you forgive me), then of course define a AbstractPerson abstract class is reasonable, because it can encompassing all of the other methods, the subclass only defines DoSomethingInWC (), greatly reducing the amount of duplicate code.

However, if the two classes of "Women" and "Man" in our program have little code in common, and there is a PersonHandle class that needs to instantiate them, and we don't want to know whether they are male or female, but just treat them as human beings and implement polymorphism, then it is necessary to define them as interfaces.

In short, an interface differs from an abstract class primarily in its motivation for use, not in itself. Whether something should be defined as an abstract class or as an interface depends on the context of the context.

Furthermore, 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 simply a set of rules that its subclasses should implement. For example, it is acceptable to define vehicles as abstract classes and cars, planes, and ships as subclasses, because cars, planes, and ships are all special vehicles. Icomparable interface, for example, it is said, to implement the interface of the class must can compare, this is a rule. If the Car class - this class implements the Icomparable, just say, our Car there is a way to carries on the comparison to two Car instance, may be is more expensive than which Car, also may be bigger than which Car, it doesn't matter, but we can't say "the Car is a special kind of can compare", this is a blind on grammar.

I hope this article has been helpful to you in Java programming.


Related articles: