The difference between abstract classes and interfaces

Keywords: Java abstract class

The difference between abstract classes and interfaces

The difference between abstract class and practical application of interface

The conceptual differences between abstract classes and interfaces are familiar, such as whether there can be differences in constructor, access modifier, multiple inheritance and so on.

In addition to concepts, you need to understand what scenarios abstract classes and interfaces are applied to and why there are two different concepts: abstract classes and interfaces.

Let's give you an example of what we saw on Zhihu

Author: BWH.Steven
Link: https://www.zhihu.com/question/20149818/answer/704355929

Dogs have eat() and sleep() methods. We define this abstract concept through abstract classes and interfaces respectively

//Defined by abstract classes
public abstract class Dog {
  public abstract void eat();
  public abstract void sleep();  
}
  
//Through interface definition
public interface Dog {
    public abstract void eat();
    public abstract void sleep();
}

But how can we increase this behavior if we need to let the dog have a special skill - drill fire circle ()?

Thinking: write the ring of fire method into the abstract class together with the first two methods, but in this case, any dog that inherits this abstract class has the ring of fire skills. It is obviously inappropriate to write the ring of fire method into the interface together with the first two methods. When you need to use the ring of fire function, you must implement the eat() and sleep() methods in the interface (Rewriting all the methods in the interface) is obviously not appropriate, so how to solve it?

We can think about it carefully. Eat and sleep are both behaviors that dogs should have, and the behavior of drilling fire circle is trained after the day. It can only be regarded as an addition or extension to dogs. The two should not be in the same category. Therefore, we consider designing an interface independently for this separate behavior, including drillfirecircle () Method. Dog is designed as an abstract class, including eat() and sleep() methods. A SpecialDog can inherit Dog class and implement DrillFireCircle() interface. The following code is given:

//Define the interface, including the fire ring drilling method
public interface DrillFireCircle() {
  public abstract void drillFireCircle();
}
  
//Define abstract class Dog class
public abstract class Dog {
  public abstract void eat();
  public abstract void sleep();
}
   
//Inherit abstract classes and implement interfaces
class SpecialDog extends Dog implements drillFireCircle {
  public void eat() {
    //....
  }
  public void sleep() {
    //....
  }
  public void drillFireCircle() () {
    //....
  }
}

The reason why the dog class is designed as an abstract class without an interface is that all dogs have the behavior of eating and sleeping, and the implementation methods are consistent. The abstract class can provide the default implementation of methods. Therefore, as long as the subclass inherits this class, there is no need to rewrite the implementation methods of eating and sleeping.

Of course, Oracle has begun to try to introduce default methods and static methods into the interface to reduce the difference between abstract classes and interfaces. Now, we can also provide the default implementation method for the interface without forcing subclasses to implement it.

Conceptual differences between abstract classes and interfaces

This part of the logic is quoted from the official account of the blue bridge cloud class.

abstract class

Abstract classes are used to capture the general characteristics of subclasses. They cannot be instantiated, but can only be used as superclasses of subclasses. Abstract classes are templates used to create subclasses at 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 HttpServlet class inherits GenericServlet, it provides the implementation of 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 collection of abstract methods. If a class implements an interface, it inherits the abstract methods of the interface. This is like a contract pattern. If the interface is implemented, you must ensure that these methods are used. An interface is only 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 of abstract classes and interfaces

parameterabstract classInterface
Default method implementationIt can be implemented by defaultThe interface is completely abstract. It has no method implementation at all
realizationThe subclass uses the extends keyword to inherit the abstract class. If the subclass is not an abstract class, it needs to provide the implementation of all declared methods in the abstract class.Subclass uses the keyword implements to implement the interface. It needs to provide the implementation of all declared methods in the interface
constructor Abstract classes can have constructorsAn interface cannot have a constructor
Differences from normal Java classesIt is no different from ordinary Java classes except that you cannot instantiate abstract classesInterfaces are completely different types
Access modifier Abstract methods can have public, protected, and default modifiersThe default modifier of interface method is public. You cannot use other modifiers.
main method Abstract methods can have a main method and we can run itThe interface has no main method, so we can't run it.
Multiple inheritanceAbstract methods can inherit a class and implement multiple interfacesAn interface can only inherit one or more other interfaces
speedIt's faster than the interfaceThe interface is a little slow because it takes time to find methods implemented in classes.
Add new methodIf you add a new method to an abstract class, you can provide it with a default implementation, so you don't need to change your current code.If you add methods to an interface, you must change the class that implements the interface.

Posted by guymclaren on Thu, 16 Sep 2021 16:30:53 -0700