Java abstract classes and interfaces, this is enough

This article talks about Java's abstract classes and interfaces. In the short song line, Cao Cao made an advertisement worth 100 million yuan for...

This article talks about Java's abstract classes and interfaces.

In the short song line, Cao Cao made an advertisement worth 100 million yuan for Dukang liquor - "how to solve the problem? Only Dukang". I feel sorry for Cao Cao that he won't receive this expensive endorsement fee. Think about it. If the stars in the Three Kingdoms period had this sense of endorsement, they would have a significant source of military revenue.

However, can wine really solve the problem? I can't believe it. Li Bai once questioned: "raising a glass to relieve sorrow is more worrying, and the water is more flowing when drawing a knife and cutting off the water." Li Bai and I share the same view. Wine is really not easy to relieve the worry, but it can definitely increase the author's inexplicable writing impulse.

I had a drink before I wrote this article, which aroused my strong desire for creation. However, I would like to advise you that in the cold winter, if you are upset, do not wantonly pursue a drunken break, and know that everything is enough.

01. Abstract class

In Java, the class defined by the keyword abstract is called abstract class. Java is an object-oriented language, so all objects are described by classes, but conversely, not all classes are used to describe objects, and abstract class is one of them.

The following example shows a simple abstract class:

// In my opinion, a coach must be both offensive and defensive abstract class Coach { public abstract void defend(); public abstract void attack(); }

In an abstract class, there is at least one abstract method (a method defined by the keyword abstract, and there is no method body, such as the extend() method and attack() method in the above example). Otherwise, it is unnecessary to call it an abstract class. Note that abstract classes cannot be instantiated It needs to be inherited by a subclass, as in the following example.

abstract class Coach { public abstract void defend(); public abstract void attack(); } class Hesai extends Coach { @Override public void defend() { System.out.println("Defense wins the championship"); } @Override public void attack() { System.out.println("Control is a double-edged sword"); } } public class Demo { public static void main(String[] args) { Coach moliniao = new Hesai(); moliniao.defend(); moliniao.attack(); } }

We all know that a good Coach must have both attack and defense, but each Coach's attack concept and defense concept are different. Therefore, I define two abstract methods in the Coach: attack and defense. The concrete implementation of these two methods is determined by the subclass of the abstract class. The abstract class itself is not responsible.

We all know that Jose Mourinho is the top coach in football. He is my favorite football coach, not one of them. Despite his own reasons for his failure at Manchester United, I still adore him because: "please don't say I'm arrogant, because I'm just telling the truth, I'm a European champion, so I'm not a nameless native, but a special one!" He is a stubborn anti - ball - control doctrine, firmly believe that the ball is a double-edged sword, defense to win the championship.

OK, let's summarize the abstract class briefly:

1. Abstract class cannot be instantiated.
2. An abstract class should have at least one abstract method, otherwise it has no meaning.
3. Abstract methods in abstract classes have no method body.
4. The subclass of an abstract class must give the concrete implementation of the abstract method in the parent class, unless the subclass is also an abstract class.

02, interface

We know that a class with abstract methods is called an abstract class, which means that there can be methods in an abstract class that are not abstract methods. Such a class can't be regarded as a pure interface, although it can also provide the function of interface -- it can only be said that abstract class is a middle way between ordinary class and interface.

Interface, an abstract type in Java, is a collection of abstract methods; the interface is defined by the keyword interface. The differences between interface and abstract class are as follows:

1. Abstract classes can have methods of method bodies, but interfaces do not.
2. The member variable in the interface is implicit static final, but the abstract class is not.
3. A class can implement multiple interfaces, but can only inherit one abstract class.

The following example shows a simple interface:

// Implicit abstract interface Coach { // Implicit public void defend(); void attack(); }

The interface is implicitly abstract, so it is unnecessary to use abstract keyword when declaring; every method of the interface is implicitly abstract, so it is also unnecessary to use abstract keyword; methods in the interface are implicitly public.

Like an abstract class, an interface cannot be instantiated directly. It needs a class to implement it, as shown in the following example.

class Hesai implements Coach { @Override public void defend() { System.out.println("Defense wins the championship"); } @Override public void attack() { System.out.println("Control is a double-edged sword"); } } public class Demo2 { public static void main(String[] args) { Coach moliniao = new Hesai(); moliniao.defend(); moliniao.attack(); } }

To implement an interface, you need to use the keyword implements, which means: "my class complies with the interface protocol. If you want to use me, just look at the interface, and don't care about the specific implementation."

03. Implement multiple interfaces

In real life, Jose Mourinho is not only a football coach, but also a hero worthy of respect. With his own efforts, he has gradually transformed from an unknown translator to a well-known top coach.

If you want to embody Jose Mourinho's multiple roles in the world of programs, you can use interfaces, as shown in the following example.

package com.cmower.java_demo.nine.inf; interface Coach { // Implicit public void defend(); void attack(); } interface Hero { void fight(); } class Hesai implements Coach, Hero { @Override public void defend() { System.out.println("Defense wins the championship"); } @Override public void attack() { System.out.println("Control is a double-edged sword"); } @Override public void fight() { System.out.println("As long as there is a moment left, we should fight to the end"); } } public class Demo2 { public static void defend(Coach coach) { coach.defend(); } public static void fight(Hero hero) { hero.fight(); } public static void main(String[] args) { Hesai moliniao = new Hesai(); defend(moliniao); fight(moliniao); } }

It can be seen that the created Hesai objects can be transformed into Coach and Hero, and then call the specific methods implemented in their respective interfaces, because Hesai implements two interfaces at the same time, namely Coach and Hero (class Hesai implements Coach, Hero, separated by English commas between interfaces).

04. Three common modes of interface in application

In the field of programming, good design patterns can make our code more efficient with less effort. When using interfaces, three modes are often used, namely policy mode, adapter mode and factory mode.

1) strategic mode

The idea of policy pattern is to encapsulate each algorithm into an implementation class with a common interface for a group of algorithms. The designer of the interface can change the algorithm without affecting the caller. An example is as follows:

// Interface: Coach interface Coach { // Method: Defense void defend(); } // Jose Mourinho class Hesai implements Coach { @Override public void defend() { System.out.println("Defense wins the championship"); } } // Depp Guardiola class Guatu implements Coach { @Override public void defend() { System.out.println("Attack is the best defense"); } } public class Demo { // Parameter is interface public static void defend(Coach coach) { coach.defend(); } public static void main(String[] args) { // Passing different objects for the same method defend(new Hesai()); defend(new Guatu()); } }

The demo. Defer () method can accept coaches of different styles and generate different behaviors according to the passed parameter objects, which is called "policy mode".

2) adapter mode

The idea of adapter mode is to transfer the original interface according to the needs of the caller. The most common adapter in life is the HDMI (High Definition Multimedia Interface) cable, which can send audio and video signals at the same time. An example of the adapter pattern is as follows:

interface Coach { void defend(); void attack(); } // Abstract class implements interface and collocates empty method abstract class AdapterCoach implements Coach { public void defend() {}; public void attack() {}; } // New class inheritance adapter class Hesai extends AdapterCoach { public void defend() { System.out.println("Defense wins the championship"); } } public class Demo { public static void main(String[] args) { Coach coach = new Hesai(); coach.defend(); } }

There are two methods defined in the Coach interface (defer() and attack()). If the class directly implements the interface, two methods need to be implemented.

If we only need to implement one of the methods, we can use an abstract class as the middleware, that is, adapter coach, to implement the interface with this abstract class, and leave the methods in the abstract class empty (the method body only has a pair of curly braces). Then, the new class can bypass the interface, inherit the abstract class, and we can only enter the required methods Row overrides, not all methods in the interface.

3) factory mode

It's not hard to understand the so-called factory model, that is, what factories produce, for example, BMW factory produces BMW, Mercedes Benz factory produces Mercedes Benz, A-level college graduates A-level coach, C-level college graduates C-level coach. An example is as follows:

// coach interface Coach { void command(); } // Coaching Academy interface CoachFactory { Coach createCoach(); } // A-level coach class ACoach implements Coach { @Override public void command() { System.out.println("I am A Certificate level coach"); } } // A-level coach College class ACoachFactory implements CoachFactory { @Override public Coach createCoach() { return new ACoach(); } } // C coach class CCoach implements Coach { @Override public void command() { System.out.println("I am C Certificate level coach"); } } // C-level coach College class CCoachFactory implements CoachFactory { @Override public Coach createCoach() { return new CCoach(); } } public class Demo { public static void create(CoachFactory factory) { factory.createCoach().command(); } public static void main(String[] args) { // For a team, you can go to any college if you need any kind of coach // The college will introduce the coach of the corresponding level of the team. create(new ACoachFactory()); create(new CCoachFactory()); } }

There are two interfaces, one is Coach, which can command(); the other is Coach factory, which can create Coach (). Then the ACoach class implements the Coach interface, the ACoachFactory class implements the CoachFactory interface, the CCoach class implements the Coach interface, and the CCoachFactory class implements the CoachFactory interface. When A-level Coach is needed, go to A-level Coach College; when C-level Coach is needed, go to C-level Coach college.

By analogy, we can also use the BCoach class to implement the Coach interface, and the BCoachFactory class to implement the CoachFactory interface, so as to constantly enrich the coaching echelon.

05, summary

Although the interface makes the abstraction further, any abstraction should be generated according to the real needs, so the proper principle is to choose the class first rather than the interface, and only refactor the code when the interface is really needed.

Last article: Java: polymorphism is the source of happiness

Next article: Are Java inner classes really so hard to understand?

WeChat search for "silent king two" public address, and then reply to the "free video" to get 500G Java high quality instructional video (Classified).

7 November 2019, 04:18 | Views: 3128

Add new comment

For adding a comment, please log in
or create account

0 comments