Abstract class
Abstract classes are used to capture the general characteristics of sub-classes. It cannot be instantiated and can only be used as a subclass of a superclass. An abstract class is a template used to create subclasses in the inheritance level. Take GenericServlet in JDK as an example:
Public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {// abstract method abstract void service (ServletRequest req, ServletResponse res); void init () {// Its implementation} // other method related to Servlet}
When the HttpServlet class inherits GenericServlet, it provides the implementation of the service method:
Public class HttpServlet extends GenericServlet {void service (ServletRequest req, ServletResponse res) {// implementation} protected void doGet (HttpServletRequest req, HttpServletResponse resp) {// Implementation} protected void doPost (HttpServletRequest req, HttpServletResponse resp) {// Implementation}/some other methods related to HttpServlet}
Interface
An interface is a set of abstract methods. If a class implements an interface, it inherits the abstract method of the interface. This is like the contract mode. If this interface is implemented, you must ensure that these methods are used. An interface is just a form, and the interface itself cannot do anything. Take the Externalizable interface as an example:
Public interface Externalizable extends Serializable {void writeExternal (ObjectOutput out) throws IOException; void readExternal (ObjectInput in) throws IOException, ClassNotFoundException ;}
When you implement this interface, you need to implement the above two methods:
Public class Employee implements Externalizable {int employeeId; String employeeName; @ Override public void readExternal (ObjectInput in) throws IOException, ClassNotFoundException {employeeId = in. readInt (); employeeName = (String) in. readObject () ;}@ Override public void writeExternal (ObjectOutput out) throws IOException {out. writeInt (employeeId); out. writeObject (employeeName );}}
Comparison between abstract classes and interfaces
Parameter abstract class interface
The default method implementation can have the default method implementation interface completely abstract. There is no method implementation at all.
The implementation subclass uses the extends keyword to inherit the abstract class. If the subclass is not an abstract class, it must provide the implementation of all declared methods in the abstract class. The subclass uses the keyword implements to implement the interface. It must provide implementation of all declared methods in the interface
Constructor abstract class can have constructor interface cannot have constructor
The difference from a normal Java class is that you cannot instantiate an abstract class. It has no difference with a normal Java class. Interfaces are completely different types.
The access modifier abstract methods include public, protected, and default. The default modifier is public. You cannot use other modifiers.
The main method abstract method can have the main method, and we can run its interface without the main method, so we cannot run it.
Multi-inheritance abstract methods can inherit one class and implement multiple interface interfaces can inherit only one or more other interfaces
Speed: it is a little slower than the interface speed, because it takes time to find the method implemented in the class.
Add a new method if you add a new method to the abstract class, you can provide it with the default implementation. Therefore, you do not need to change your current code. If you add a method to an interface, you must change the class that implements the interface.
When to use abstract classes and interfaces
If you have some methods and want some of them to have default implementations, use the abstract class.
If you want to implement multi-inheritance, you must use interfaces. Because Java does not support multi-inheritance, subclasses cannot inherit multiple classes, but can implement multiple interfaces. Therefore, you can use interfaces to solve it.
If the basic functions are constantly changing, you need to use abstract classes. If you constantly change basic functions and use interfaces, you need to change all classes that implement the interfaces.
Default and static methods in Java 8
Oracle has begun to introduce default and static methods to interfaces to reduce the differences between abstract classes and interfaces. Now, we can provide a default implementation method for the interface and do not need to force subclass to implement it. I will describe this type of content in the next blog.
Abstract classes and interfaces do have many similarities, but in essence, or from the perspective of language design, this is not the essential difference between them.
My personal understanding of the two:
A class is the abstraction of a specific instance, such as the abstraction of a json string; an abstract class is the abstraction of a class; an interface is the abstraction of an abstract class, and an interface is more like a protocol.
Listen to me ~
Tucao
First of all, I have to talk about this interview. I think the interviewer asks such questions as "talking about the differences between abstract classes and interfaces" and "talking about the differences between processes and threads, is not responsible.
Why?
One reason is that the interviewer does not have his or her own rating for the target person, and the other reason is that he or she is not responsible for the subject. This problem cannot be used to test the interviewer's level.
So if I come to interview someone else, I will ask: could you tell me how you understand abstract classes and interfaces? If you want to explain the difference between processes and threads to your grandmother, how would you explain them?
I think this can test the interviewer's understanding of the problem. I think Microsoft's interview questions (how do you explain Excel to your grandmother) can also test a person's understanding of something (although, so far I still cannot quite understand this question -. -)
Differences between abstract classes and interfaces
When talking about abstract classes and interfaces, you must talk about classes.
A class is the abstraction of real things.
For example, to define a BenzCar class, you need to have a good abstraction of the real Mercedes-Benz Cars (of course, there are many series of Mercedes-Benz cars, which won't be a perfect place here ). That is to say, if you want to build a Mercedes-Benz car, you need BenzCar (this Mercedes-Benz car is an Instance in memory ).
The abstract class is the abstraction of the class.
How can this problem be solved? That is to say, many Car manufacturers define a specification (Car type) together. To build a Car, there must be an engine, tires, and sound equipment... (These are equivalent to abstract methods.) the specific engine, tires, and audio equipment used are completed by each vehicle manufacturer. In this way, there will be a variety of cars, the Mercedes-Benz brand, the BMW brand, the Toyota brand...
An interface is an abstraction of an abstract class.
This is my personal understanding.
In our daily life, we can see various "interfaces", and the power outlet is one. At first, I saw Uncle mouse's blog start to understand the concept of "control flip"-IoC/DIP is actually a management idea. Later, I thought that this thing is actually everywhere. The factory that manufactures power sockets and the factory that manufactures electrical appliances only need to agree on an interface-two or three sockets, of course, interfaces in different countries are different, and the conversion between different interfaces requires an adapter.
In fact, the same is true in the program. For example, all transportation tools can be abstracted as an interface Drivable (I may not think well due to experience ), indicates that the objects created by the class implementing this interface (such as cars, airplanes, ships, and so on) can all be driven.
Public interface Drivable {
Public void drive ();
}
Then, we can create a AbstractCar class, which indicates that this class is an abstraction of all automobile classes. All cars that can drive must inherit this class. This abstract class specifies some abstract methods, for example, the getEngine () method indicates that the engines of each car are not the same and must be customized in the subclass (of course, you can inherit the AbstractCar class, abstract all vehicles that may have the same engine ).
Why is the drive () method of Drivable implemented by default, but the default implementation directly throws an exception?
In fact, this is an interface implementation method, and another method is to set drive () to abstract. The two implementation methods are the same in terms of functions, but they are different in terms of class design.
The implementation in the following code refers to the design of the add (int location, E object) method in java. util. Javasactlist <E>. It is written in the document:
* @ Throws UnsupportedOperationException * if adding to this List is not supported. public abstract class AbstractCar implements Drivable {public abstract Engine getEngine (); public abstract Wheel getWheel (); @ Override public void drive () {throw new UnsupportedOperationException ();} // omit other methods and attributes}
The drive () in the above code can be understood:
By default, "Cars" cannot be opened. After you implement a car class, you need to Override this method to implement your own drive method.
Take the List in the java container as an example.
Find the source code and you will find that the top level of the inheritance relationship of List <E> is Iterable, which means that List can be traversed, it also generates an Iterator interface object. This indicates that a list can be traversed through this iterator.
As mentioned above, all vehicles can be driven, and all lists can be traversed.
A layer-by-layer approach makes the class more specific.
Last
Why can interfaces be inherited?
In fact, this principle is very simple. Because there is always a most essential protocol to constrain everyone, for example, all the means of transportation can be driven, all the easy to traverse. Then the protocol will gradually become more specific:
Iterable <-Collection <-List <-AbstractList <-List
From the bottom up, it is a layer-by-layer abstraction.
As I said at the beginning of the article,
You can use the ArrayList class to create many objects. ArrayList is an abstraction of these objects.
AbstractList is an abstraction of ArratList. You can use AbstractList to create ArrayList, Stack, or rollback list.
The List interface is the abstraction of all List classes.
Collection is the abstraction of containers with all single elements.
Iterable is a high-level abstraction, indicating that all containers can be traversed.