Hello, I am a pig program ape, usually like to toss technology, raise “pig”, will not regularly share some technical articles. Pay attention to me, do not get lost ~
How to choose an abstract class or an interface
preface
Abstract classes and interfaces are familiar to Java and C++ programs, but do you know how to use abstract classes and interfaces correctly? Are you still equivocating, simply memorizing the difference between the two, and not knowing what to do in a real situation?
Today, I’m going to walk you through the differences once and for all. Of course, this article is based on Java, but it works just as well for programs in other languages
What is abstract class? What is an interface?
Here take care of the beginners of the program ape, a brief introduction to the definition of these two.
Abstract classes: Exist for inheritance.
Interface: Something more abstract than an abstract class.
The introduction is really very simple, but I still don’t know how to choose which one of them… Then look!
The difference between abstract classes and interfaces
In fact, I also summarized the difference between the two, as follows:
An abstract class:
(1) The abstract method must be either public or protected (because if it is private, it cannot be inherited by subclasses and subclasses cannot implement the method), and public by default.
(2) Abstract classes cannot be used to create objects.
(3) If a class inherits from an abstract class, the subclass must implement the abstract methods of the parent class. A subclass must also be defined as abstract if it does not implement the parent class’s abstract methods.
(4) The member variables of an abstract class can be of any type.
(5) You can have static code blocks and static methods.
(6) A class can inherit only one abstract class.
(7) Class is “is not the relationship”.
Interface:
(1) Variables can only be defined as public static final.
(2) Methods can only be abstract, there is no method body.
(3) No static code blocks or static methods.
(4) A class can implement multiple interfaces.
(5) The interface is “does it matter”.
(If you need some notes compiled by myself, you can follow the program ape of pig raising on public account, and I will share them later)
Of course, these differences only apply to Java8 before, Java8 interfaces could have default methods, static methods, and these new features are described below.
With these differences in mind and some of the new Java8 features in mind, the interview should be no problem. However, the interviewer may ask you to give real examples or give you scenarios to choose from, which can be problematic for candidates who only memorize interview questions. But don’t panic, I’m going to take you through a very real-life example to help you understand how to choose once and for all!
How to choose?
In fact, the above distinction has been written, abstract class is a “no” relationship, and interface is a “no” relationship. Therefore, it is easy to imagine that abstract classes should be common features of a class of things, such as a Person, who has eyes and skin color, which describe a Person can be defined in an abstract class, and a Person’s behavior, such as playing basketball, can be defined in an interface.
This example is actually not too obvious, LET me take a real example of a program ape, through the actual combat to speak!
For a programmer. You must get up at the beginning of the day, so you need to maintain a variable — the wake up time. Because everyone’s wake up time is different, it is a state quantity, so this wake up time cannot be modified with final, so the interface passes, only use abstract class to maintain this variable.
Then you go to work and you clock in, and you can use a function to describe how you clock in. I assume that every company here requires hh (of course, I have stayed in the company has some flexibility, do not need to clock HH), so this is the commonality of every program monkey, should also be maintained in the abstract class.
The life of a programmer can be more than just writing code. You can have some hobbies like playing basketball, but not every programmer likes playing basketball, so it’s easy to decide which interface to choose to maintain this interest.
At this point, let’s write the code:
// Program ape base class
public abstract class BaseWorker {
// Wake up time
protected int wakeupTime = 7;
// Punch in protected abstract void clockIn(a); } Copy the code
Protected is used primarily for inheritance, so that subclasses can access it.
public interface Interest {
void playBall(a);
}
Copy the code
// A programming ape
public class Worker extends BaseWorker implements Interest {
protected int wakeupTime = 6;
@Override
protected void clockIn(a) {
/ /... } @Override public void playBall(a) { / /... } } Copy the code
However, LET me tell you that the choice of abstract classes and interfaces is not arbitrary and should be tailored to the business. For example, everyone in our company likes to play golf, so if we still define playing interest in the interface, we need to implement the interface every time, which has a large amount of redundant code. So, in this case, we can put the ball into a new worker abstract class, which can reduce the amount of implements.
The code is modified as follows:
// Programmers love to play ball
public class WorkerLikeBall extends BaseWorker{
protected abstract void playBall(a);
}
Copy the code
In this way, you only need to inherit BaseWorker to get the wake-up time and clock in to work. On the surface, it does not conform to the specification of abstract classes I mentioned earlier, but it is more in line with our appeal. Only flexible use can write simple and efficient code.
The default and static methods of the interface
Finally, let’s talk about default methods and static methods for interfaces, which are new to Java8.
Java8 can write static methods in its interface, such as the new Comparator, which added static comparing methods and passed a function interface.
List<Integer> list = Arrays.asList(1.2.3.4.5);
int min = list.stream().min(Comparator.comparing(value -> value)).get();
int max = list.stream().max(Comparator.comparing(value -> value)).get();
Copy the code
You can also add static methods to your interface without affecting the use of the original code (you don’t have to override this method in the implementation class).
public interface Interest {
void playBall(a);
default void start(a) {
System.out.println("start playing"); } static void time(a) { System.out.println( LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME) ); } } Copy the code
The default method, the default modifier, the implementation class can not implement the default method, if the subclass implements it, then use the default method implemented by the subclass. The core of the default method is that it is compatible with previous code and easy to extend.
Multiple inheritance of default methods: If the implementation class implements multiple interfaces, and each interface has a default method of the same name, Then Java cannot determine which one to use. In this case, the implementation class overrides the method, because overrides have the highest priority.
Static methods are called only by the name of the interface, so there are no multiple inheritance problems.
Why abstract classes when Java8 has such a strong interface?
Again, existence is reason.
First of all, the original design of adding default methods to Java8 was to leave the other implementation classes unchanged without changing the interface.
For example, the List interface in Java has added the default method sort in Java8, so that other classes implementing the List interface can inherit this method and use it without modifying it. After all, functional interfaces are so popular that more and stronger default methods will be added to the interface.
But for state class variables, you still need to put them in an abstract class.
Hello, I am a pig program ape, usually like to toss technology, raise “pig”, will not regularly share some technical articles. Pay attention to me, do not get lost ~
This article is formatted using MDNICE