Differences between Java Abstract classes and interfaces (csdn comment)

Source: Internet
Author: User

Original: http://topic.csdn.net/t/20030921/23/2285054.html

"What is an interface, why is an interface used, and how can I use it properly ?"

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Wulemale)

An interface is required to implement multi-inheritance.
For example, to define a small multi-threaded application class, one of the implementation methods is as follows:
Public class threadtest extends applet implements runnable
{
Threadtest mytest = new threadtest ();
Thread mythread = new thread (mytest );
Mythread. Start ();
}

 

 

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Smart pig)

An interface is used to define the desired function when your module needs to provide a function.
It serves as a specification for your needs, a description.
You use an interface to precisely describe the required "functions" and then receive an object for this interface from the outside world.
Then you can use this interface.

It allows you to focus on "interfaces" and "specifications", rather than "Implementation ". How others implement it is what others do, and it has nothing to do with me. You can encode, compile, and test the things you need to implement, even if the functions you need are not implemented by others.

As needed, others can pass different interface implementations to your module to achieve the purpose of reuse.

For example:
You can write a travel guide: "Take a bus to Beihai, have lunch here, and go to the Palace Museum in the afternoon ."
As for bus, taxi, steamed stuffed bun or McDonald's, how can we go to the Palace Museum in the afternoon? do not go beyond the limit. Users can decide based on their objective conditions.
Therefore, taking a bus, taking lunch, and going to the Palace Museum are all interfaces. You only need to write the logic you care about. As for implementation details that you don't care about, use interfaces to abstract them.

Finally, interfaces are irrelevant to multi-inheritance.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Zheng)

 

It can be viewed from the perspective of reuse.

For example, I have a class: classa
Many programs use this classa and write it in the code. If there is a classb later, the function is better than classa, and I want all the places where classa is used to become classb, it will be very troublesome.

However, if I implemented an iclass interface in classa, all the code is compiled for iclass, and a factory class is used to instantiate the classa. In this way, when I need to replace all classa with classb, I only need to implement iclass for classb, and then replace the instance that returns classa with the instance that returns classb in the factory class.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Csdnhbc20)

 

The interface is relatively unchanged, that is, stable. Therefore, when defining an interface, you need to find the essence and put it in the interface, this is the so-called interface's eternity, but in fact it is impossible to reach the eternity, because the specific environment is changing, and the essence of the software is changing, therefore, there is no way to define an eternal interface.
I think it is mainly a few common oo principles to abstract the interface methods:
1: OCP principles
2: Li's replacement principle (where the parent class can be used, the subclass can certainly be used)
3: Dependency inversion principle (dependent interface class, independent of implementation class)
....
In actual work, the main thing is to have a detailed analysis of the Product Industry (that is, the demand analysis phase)
, Can fully understand the system field, so as to anticipate the changes in the system, in order to abstract a better object out
In this way, the system you do is naturally satisfied by the customers. Therefore, we actually need to expand our horizontal thinking capabilities with profound humanistic, psychological, and social knowledge, in this way, we can grasp the requirements of the system more realistically, and also require strong ability to receive new problems and learn independently.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(An idiot with the same genius)

 

An interface can be seen as something similar to an abstract class. It only cares about some commonalities, but does not provide implementations.
I think it is important to figure out when to use abstract classes and interfaces.
In general, an abstract class is the relation of is something, and an interface must describe the relation of has something.
For example, if you can define an interface lock, there may be a variety of locks, locks, car locks, computer locks, and so on. Their features are like Lock unlock, but the specific locks, such as doors, cars, and computers, should be written in the specific definitions of these locks. Even the door lock is an abstract class. The car lock is an abstract class. The computer lock is an abstract class. They all declare the lock interface. Then I can inherit the anti-theft lock from these abstract classes, computer locks and so on

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Xuefeng)

 

 

Interfaces completely separate class definitions and implementations.

The class provider provides the customer with an interface to ensure that all functions defined by the interface are implemented. As for how to implement the interface, it is not related to you.

As a client, you only need to care about the functions provided by the interface and use the interface.

This minimizes the coupling between the layer and the layer, and the provider may change the implementation class, but the client does not need to change as long as the interface remains unchanged.

The most important aspect of Java programming is that it only targets abstract programming.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Shu Ren)

The interface is about the type, while the class is about implementation. There are data members in the class. If the class is modified, the client must be reconnected or even compiled. Through the interface, you do not need to re-compile and connect.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Jeffyan77)

 

Bruce007 is close to my point of view: interfaces are about types, while classes are about implementation.

Do not use interfaces for some convenience.

The advantages of using interfaces mentioned above are basically pure types and the advantages of separating pure types from implementations. Are correct.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Zhao mingyu)

 

1. In terms of requirements, the interface displays the results of your requirement analysis. It is the product of demand analysis. After you finish the requirement analysis, you can get the methods required by each department of the system. Remember, it only reflects what the system wants to do, not what the system should do. When you think that the interface you define fully meets all the functions required, it is best to manually simulate the system operation.
For example, you can "call" methods in your interface while looking at your use case diagram and sequence diagram (not just those. This call is called in your mind. Assume that all the implementations have been completed and are very correct.

If the system "runs" well in your mind. It indicates that you have completed the design of the system upper layer (on the premise that your requirements are correct ). Next, you can implement the "implementation of different requirements under the methods defined by the interface" for the interface you designed to realize the polymorphism of different business rules and responsibilities for the same business.. Remember that an interface is a mechanism for implementing polymorphism (of course, an abstract class is also acceptable ).

2. From the design perspective: Java advocates abstract programming (as long as it is an object-oriented language ). Specifically, the client should only rely on abstract things. Specifically, the client should only program the interface. Do not apply to specific implementations. In this way, when the business rules for implementing this interface change, you only need to modify the subsequent implementations without affecting the client, because the client does not know that you have secretly changed the specific implementation of the method. This minimizes the impact on the system by changing the system. By the way, the client is not a client. The client is relative. A calls B, and A is called B. B is the server of A. Generally, in a system, the upper layer is the client at the next layer. The next layer is the server of the previous layer. Each part of a system may call each other, so they are also the relationship between the client and the server. The server only provides the necessary methods to the client. When each part of the system is called through an abstract interface, each part has a stable "contract ", they communicate with each other based on the contract, and do not know how the other party implements the contract. In this way, you have a lot of room to choose the specific implementation details of each part and how to implement it. Thus, their clients are not affected at all. This situation is most evident when the implementation rules change and you need to rewrite the implementation. This is also the reason for abstract programming.

3. From the object-oriented perspective: the object-oriented technology provides us with many good features. For example, information hiding and polymorphism. Information Hiding is encapsulation, while polymorphism is inheritance. (The implementation of the interface can be seen as an inheritance. Although it does not inherit anything from the "father", it is still your father ^_^ ). Using interfaces, we can fully utilize the characteristics of polymorphism. Polymorphism is one of the most important characteristics of object-oriented systems. If you do not need an interface or abstract class, but simply use each specific class to do things, you can say that you have only achieved the advantages of encapsulating information from the object-oriented perspective, but the biggest benefit of polymorphism is lost. Such a program does not actually use object-oriented technology. So with object-oriented, the most important thing is to use its polymorphism. The interface is the path to polymorphism.

The above is my personal opinion from my experience. Let's continue to discuss it.

 

(Zhao mingyu)

 

By the way, there are many inheritance issues. The interface does not exist because of Multi-inheritance. The most important purpose of the interface is not multi-inheritance. It is because JAVA does not support multi-inheritance, and interfaces can be used to indirectly implement this type of property. Therefore, it is common to feel that interfaces occur due to multi-inheritance. This is a big mistake.
I personally feel that the inheritance of this feature greatly increases the complexity of design, and the benefits it brings are not as great as the disadvantages it brings. Do not use multi-inheritance during design. There is a reason why Java has canceled the multi-inheritance nature.

 

(Zhao mingyu)

Inheritance should be used, but do not transition dependencies, as ajoo (smart pig) said.

During design, we should first consider aggregation and combination, and secondly consider inheritance. Inheritance is a static reuse method, and the aggregation relationship between objects is dynamic reuse. Don't just inherit the class because a class already provides most of the code you need and you want to add more. This is often a wrong idea. Inheritance must satisfy the is-a relationship. That is to say, you can inherit only when the subclass is a parent class. The is-a relationship is a necessary condition for intra-style replacement.

 

(Zhao mingyu)

 

// This is an interface. vehicle is the meaning of the vehicle. This interface defines a common method of the vehicle.
// Drive () Driving
Public interface infvehicle {
Public void drive ();
}

// A car is a vehicle and an interface for implementing a vehicle.
Public class car implements infvehicle {
Public void drive (){
// The car driving method is implemented here
}
}
// Bicycles are also vehicles, implementing interfaces for transportation
Public class bicycle implements infvehicle {
Public void drive (){
// Here, the bicycle driving method is implemented.
}
}

// This is a "person" class. One of its methods is Gohome. Returning Home requires a transport, so he has a transport that he uses when going home.
Public class man {
Private infvehicle vehicle;

Public infvehicle getvehicle (){
Return this. vehicle;
}

Public void setvehicle (infvehicle vehicle ){
This. Vehicle = vehicle;
}
// Return Method
Public void Gohome (){
This. vehicle. Drive ();
}
}

Now let's look at how to use these classes

Man Aman = new man (); // create a "person"
Infvehicle car = new car (); // create a car
Infvehicle bicycle = new bicycle (); // create a bicycle

// For example, if this person wants to drive home today, we will
Aman. setvehicle (CAR );
Aman. Gohome ();
// If he is tired of driving, he can ride his bike home in another way.
Aman. setvehicle (bicycle );
Aman. Gohome ();

-----------------------------------------------------------------

The advantage of such code is that if one day the person said, "I don't want to drive a car. I don't want to drive a bicycle. I'm too tired. I want to drive a big truck home from work. That's handsome enough !" (Note: customers can make similar requests.) What should we do? Here, people use transportation services. People are clients, and transportation services are servers (one of my posts mentioned above is about clients and servers ), we do not want to influence the client. This is because the interface is used in this example. For example, we can add a sixby truck class to implement the interface for transportation. If this person wants to drive a truck home from work, he will pass it to a sixby instance, and he will be handsome enough.
Of course, there is a problem here, but the interface discussed in this post is irrelevant. How can we create specific transportation tools? Is there a new one every time you want to change the transportation? To solve this problem, you can consider the design model of the factory. This is far away from the topic.

(Zhao mingyu)

 

(Xiaoer)

Maybe I am a little dumb. I have talked so much about the above, but I still don't understand the differences between interfaces and abstract classes. can abstract classes achieve polymorphism? Just like the example written by truezerg (Zhao mingyu), I feel that if an abstract class is declared, these methods can be reloaded in actual use, which can achieve this effect.
I asked my colleague just now. He said that the interface is flexible, and it is a bit confusing to give you an interface for remote access.

 

(Zhao mingyu)

To: yangjuanli (Hangzhou)
The example I wrote above is very simple. I just want to express how to use interfaces. Of course, in that example, if you can find one thing that all transportation means share in driving, you can also use abstract classes. In this case, you can transfer the common place to the parent class. In this case, you can use abstract classes.
Note that the interface is more closely related to abstraction, and the abstract class is more closely related to implementation (compared with the interface, although it is called an abstract class ). Therefore, you must pay special attention to and be careful when it comes to implementation. You must make sure that the code you put in the abstract class must be suitable for all its sub-classes. If not, or you are not sure, you can use the interface better.
In addition, my personal suggestion is that you should always define an interface for the user no matter whether you have extracted common code or whether you have used abstract classes. Even if you have an abstract class, you must provide an interface for your abstract class to implement your interface. Your subclass inherits your abstract class. Send the interface to the user. This makes it better.

 

Breakpoint_fish@hotmail.com

Welcome to join us!

 

 

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

 

(Autumn tree)

 

For example, J2EE and sun have released a new specification that uses all interfaces. Other people such as IBM and Bea only need to implement these interfaces according to Sun's documents. If sun releases an implementation instead of an interface, such as a class, IBM says that I hate sun's implementation, and its efficiency is too low. It is not that easy to switch to its own implementation. Interface is a good tool for abstracting specifications.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Smart pig)

 

When I write a thread pool, I find that thread is a class rather than interface, which makes me very uncomfortable. A lot of things have to be done around a big bend, but they are not clean.
It seems that this is a disadvantage of Java.

In addition, he agreed with Zhao mingyu's Criticism of inheritance. The transition dependency on inheritance (or even the inheritance of OO) comes from the influence of languages such as Smalltalk And Simula, and the inheritance of "inremental design" can naturally describe the innocence of the world.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Csdn can be used whenever and wherever possible)

 

The following example shows the interface polymorphism.

A woman has a private place.
A man has a stick and can operate the interface. The same man's stick can operate on different women (as long as they are women and have a mouth), but men only know that this woman is a woman. I don't know whether it is Zhang Sanmei or Li simei, at this time, it is said that women are polymorphism (think about the multi-person adult party after the light is turned off, and everyone will not speak, and they will catch it ). For the color wolf, he only recognizes people who have a mouth and does not pick out three sisters or four sisters.

Comparison:
Men: customers, consumers
Definition of Women: Women
Men and women: all consumers can be consumed.

 

The above has repeatedly stressed that women are talking about, so the female, sow, and cow also have a mouth, is it true that men may also consume them? The answer is yes. In this way, it cannot be inferred that because a woman is a human, a bitch, a sow, and a cow are also human, she (IT) is a mother. This is the interface. A woman can implement, a bitch, a sow, and a cow can also implement. This is what the role means.

Humans can use hand-made tools. This is a skill of humans. Therefore, women can also make tools, but sows and female cannot. Therefore, human-to-female is a functional implementation (all human beings ), female-to-female, female, sow, and cow are role implementations (both female ).

 

(Zheng Kansai)

 

Littlecpu (csdn, anytime, anywhere, ready for use .)
It's rough, but classic !!!
From his example, we can see that men and women are class, which can be inherited, while public pigs and sows can also be inherited,
However, all female mammals have implemented such a socket, so all male mammals have achieved plug-ins.
In this way, the creature can flourish, because it has implemented the socket and plug-in interfaces, these mammals can find a similar class of the opposite sex to work.
In fact, this is quite complicated, and female also implements another interface. Although it is all in one mouth, the functions are different. The latter is related to inheritance.
Then we can define two methods of the interface. One is mating, and the other is giving birth to a child.

For example:
Ifemale I = New Woman ();
I. Have a child ();
A child is born;

Ifemale I = new sow ();
I. Have a child ();
A pig was born;

This achieves object-oriented polymorphism.

 

(Zheng Kansai)

Abstract classes are used inside components.
The interface is used outside the component.

As for the specific implementation of human and swine interfaces, you don't have to worry about it. It is implemented by God.

Bytes ----------------------------------------------------------------------------------------------------------------------------

(The mountains are not high)

 

I am also busy,
We have discussed the advantages of many interfaces.
However, I think these are all relatively false,
It doesn't mean that every time you write something, an interface first, and then the implementation will have that benefit,
You must be able to grasp the essence of things. Otherwise, the written interfaces can only be changed.
Modify it, and expand it whenever you have trouble. It becomes cumbersome because it expands the interface
Class, sweat.

The key to understanding interfaces is to learn abstraction. abstraction is an analysis process,
To put it bluntly, it is still an object-oriented analysis problem. This is a long term, and it is not my director (people who do not have a home
In this way, sometimes I seem to understand something, but I can't say it, so I am smiling ).
A friend and I said that every object has vitality and I don't understand it at first. It makes sense to think carefully later.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Liu Yujiang)

 

You can try to detail the interface with an envelope, the address on the envelope, the zip code, the recipient's name, and the content in both are equivalent to the interface
The methods provided in, these methods are the general standards used from the sender to the post office to the recipient, you just need to put the envelope
The fill of each element is complete (that is, the interface implementation), so this letter can be identified and used in a wide range, of course, you can also
An envelope is a symbol (only the sender and specified recipient can understand). You can add an element to the envelope when implementing an envelope.
(The level is not high. Understanding may be incorrect. Please submit it)

Bytes ----------------------------------------------------------------------------------------------------------------------------

(Dedicated for defeat)

 

I still support the idea of interpreting interfaces as 'normal' or 'standard. The interface is a piece of paper, and many entries are strictly specified on the paper.
There is no error in the example of truezerg (Zhao mingyu), but it only reflects part of the connotation of the interface, and the abstract class also has this function.
I think the best example is the javawings (javawings) example. For example, if the power outlet of a building is of three holes, three holes must be used for all the plugs.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Dog thief)

 

In the next step, I learned how to write interfaces, because I found that there are still negligence and errors in details after a good object-oriented design method is adopted. For example, there is no major problem in class definition, and the method is also like this, however, during the overload, I found that I was constantly adding parameters, so that a method may be overloaded many times. Every time I had to compile all the calls, I would like to ask your predecessors, if, after I define the called interface class, do I not need to consider the consistency of parameters or returned values during the declaration, just use the same method name? Or can this problem be solved using abstract classes?

 

(Zhao mingyu)

 

No. The interface has no effect if you only consider the method name and do not consider the parameter type and number of parameters. You are constantly adding parameters in the overload so that a method may be overloaded many times. This shows that your interface definition is incorrect. If the interface does not meet user requirements, You Want To reload existing methods and add parameters when writing classes. Even if you do this, it is useless. Because there is no post-added method in the interface. You cannot use it through interfaces.

After determining whether an interface is defined, you can test whether an interface meets the requirements and then decide whether to implement it.

 

(Dog thief)

 

Thank you, truezerg (Zhao mingyu). Can you understand this? You must declare the overloading of all methods when defining the interface. As for the implementation, you can put it in the next step, but planning these methods is a prerequisite. Otherwise, there is a problem in the abstract analysis process of the class.

 

(Zhao mingyu)

 

In this case, if you often find that a method is missing or an overload method is required during interface implementation, add the method to the interface and then implement it. This indicates that your interface is not defined. It is not until you implement it that it does not meet your needs, so you can change it. This is not good.

In my personal experience, if there are too many overload methods in the interface, it is very likely that it is not well designed. Generally, the interface represents the service on the previous layer. Services are generally relatively stable, with too many overload methods and unstable parameter export interfaces. In addition, it seems that it is not necessary from the service perspective. It's just my personal thoughts.

 

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Sagaman)

 

Excuse me: Where are the interfaces in the Java. SQL package implemented? The getconnection method of the preparedstatement object returns the connection object, and then you can directly use the method of the connection object, which is not applied as Zhao mingyu said.

In addition, how do I enumerate all constant attributes of an interface? For example, if I want to prevent all types of education from accessing the education interface, each degree is used as an attribute of the education interface. I need to list all types of education in a certain place. How can I achieve this? Isn't all education qualifications used as an array class attribute of the interface?

 

(Zhao mingyu)

To: sagaman (sagaman)
---------------------------------------------------
Excuse me: Where are the interfaces in the Java. SQL package implemented? The getconnection method of the preparedstatement object returns the connection object, and then you can directly use the method of the connection object, which is not applied as Zhao mingyu said.
---------------------------------------------------
In fact, are you not using the connection interface? Getconnection returns a specific class object that implements this interface. Where did you implement it? In the driver of each specific database you use. You must use this sentence before connecting to the database. Class. forname (driver). newinstance (); this is to load a specific database driver.

JDBC is an excellent example of using interfaces. You just need to use the method in the interface, No matter what database driver you are using. Just like you just drive by means of transportation, No matter what car you are driving.

 

(Sagaman)

To Zhao da:
The first question: how to hide the interface implementation? For example, you don't know how to implement the resultset and statement interfaces. The implementation of these interfaces is hidden for you.

 

(Zhao mingyu)

 

What is the implementation of the hidden interface? Do you know how Oracle implements JDBC? I don't think most people care about this. But we have used its driver for Oracle database applications. When you use it, you are using the JDBC interface, that is, talking to the interface. Is this hidden?

In fact, there is no need to hide the interface implementation. Do not hide.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Volcano)

A little personal understanding.
An interface is a description of an external feature. Therefore, private and protect are invalid. Because it does not involve specific implementations, variable definitions are also invalid.
For example, interface digestion function {
Public absorption ();
Public excretion ();
}
Class is the definition of an entity rule. You can implement interfaces in the class.
For example, the class person impliment digestion function {
Eat ();
Drinking ();
Pull ();
Scatter ();
Public absorption (){
Eat or drink
}
Public excretion (){
La or SA
}
}
From the code perspective, class inheritance can reduce subclass code, while the implementation of interfaces only adds code.
Finally, there is no inheritance relationship between the interface and the interface, but only the extension relationship.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Magic eye)

The interface is the commitment to the customer.

Bytes ----------------------------------------------------------------------------------------------------------------------------

 

(Mozart2000)

In fact, it is most intuitive to use DIY computers.

The slots on the motherboard are interfaces.
As long as the interface specifications are met, you can use the product at will.
For example, you can use a dlink Nic or a 3com Nic,
You have no room to replace the motherboard that integrates the NIC.

Programming with interfaces can improve the scalability of the software.

Bytes ----------------------------------------------------------------------------------------------------------------------------

Bytes ----------------------------------------------------------------------------------------------------------------------------

Bytes ----------------------------------------------------------------------------------------------------------------------------

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.