What are the characteristics of the interface interface of learning Java from scratch? come see

The full text is about [ 5000] words, no nonsense, just pure dry goods that allow you to learn techniques and understand principles! This article has a wealth of cases and videos with pictures, so that you can better understand and use the technical concepts in the article, and can bring you enough enlightening thinking...

1. Interface Introduction

1 Introduction

The interface in Java is similar to a special abstract class, which is also a collection of many abstract methods . The definition method and components of the interface are similar to the abstract class, but more abstract and pure than the ordinary abstract class. But we can only say that the interface is similar to an abstract class, but it is not really a class. Interface and class are two different concepts. A class describes the properties and methods of an object, while an interface mainly contains the methods to be implemented by the class .

Because interfaces are not real classes, they cannot be instantiated, but they can be implemented. Usually we use the interface keyword to define an interface, and use the implements keyword to allow a class to implement one or more interfaces, thereby indirectly becoming a subclass of the interface and achieving the purpose of multiple inheritance. In general, when a class implements an interface, it must implement all the methods in the interface, otherwise the class must be declared as an abstract class .

In addition, in Java, the interface type can be used to declare a variable, which can be associated with the object that implements the interface to achieve the purpose of polymorphism.

2. Classification

In general, our so-called Java interface refers to the above concepts. But in fact, Java's interface can actually have two understanding angles.

2.1 Narrow interface

From a narrow point of view, an interface is the interface we mentioned above, which represents a kind of capability and agreement. Because Java is single inheritance, when the method in the parent class cannot meet the needs of the subclass, the ability of the subclass can be expanded by implementing the interface. The interface supports multiple implementations, which can extend various capabilities for the class. So the interface represents a certain capability, and the methods in the interface are the specific requirements for the capability.

2.2 Generalized interface

In a broad sense, an interface is a standard and specification. In order to better constrain everyone's behavior and achieve consistent goals, we can formulate unified requirements and standard specifications, which are actually a kind of interface. Just like in daily life, we often need to charge various electronic devices or transmit data, which requires charging cables and charging sockets. In the early days, the equipment produced by each manufacturer had its own socket, some were round, some were square... If you go out, you may have to bring a lot of various chargers with you. Line, otherwise everyone is not compatible with each other. This seriously reduces the customer's desire to buy electronic products and adds endless troubles to the customer. what to do? Therefore, the electronic equipment industry established a standard committee, and everyone should not fight alone. In the future, all electronic equipment produced by manufacturers will use USB sockets uniformly. In this way, even different devices can be interconnected with each other, which greatly reduces troubles and increases customers' desire to purchase electronic devices. The USB here is a unified standard and specification, this is the interface! There are countless such examples in life, and we also need such standards and norms in software development.

 

3. Features

According to the above-mentioned interface concept, Yige will extract the characteristics of the interface for you:

  • Each method in the interface is implicitly abstract , and these methods are implicitly designated as public abstract by default (only public abstract, before JDK 9, using other modifiers will report an error);
  • There can be variables in the interface, and they will become constants by default , because the variables in the interface will be implicitly designated as public static final variables (before the JDK 9 version, it can only be public, and a compilation error will be reported if modified with private);
  • Before JDK 8, the methods in the interface were not implemented by default , and the methods in the interface could only be implemented by the class that implements the interface. Starting from JDK 8, there can be a default default implementation method in the interface;
  • Starting from JDK 9, methods are allowed to be defined as private in the interface , so that some reused code will not expose the method.

4. Comparison of interface and class

Many beginners may be confused about the difference between interfaces and classes, so some interviewers will often investigate this area during interviews, so next, Brother Yi will summarize the similarities and differences between interfaces and classes.

4.1 Similarities Between Interfaces and Classes

  • Both interfaces and classes can define multiple methods;
  • Both interface and class file suffixes are .java, and bytecode files are both .class;
  • Interfaces and classes have the same naming convention, they all follow the camel case rule, and the first letter must be capitalized.

4.2 Difference between interface and class

  • Interface has no constructor;
  • Interfaces cannot instantiate objects;
  • In general, all methods in an interface are public abstract methods and cannot have default implementations;
  • There can be a default implementation in the JDK 8 start interface, and the JDK 9 start interface method can have a private method;
  • The variables in the interface are public static final variables by default and cannot contain other member variables;
  • The relationship between interface and class is not inheritance, but implementation;
  • Interfaces support multiple inheritance indirectly.

4.3 Difference between interface and abstract class

  • Abstract classes can have abstract and non-abstract methods, non-abstract methods can have concrete implementations, and methods in interfaces are generally not implemented.
  • Member variables in an abstract class can be of various types, while member variables in an interface can only be of public static final type;
  • Interfaces cannot contain constructors, static code blocks, and static methods, while abstract classes can have constructors, static code blocks, and static methods;
  • A class can only inherit one abstract class, but a class can implement multiple interfaces.

In fact, some students will be confused. Since abstract classes are very similar to interfaces, when should we use interfaces and when should we use abstract classes?

We need to know that an abstract method is essentially a specification for defining an interface. It specifies the interface of a high-level class and ensures that all subclasses have the same interface implementation, so that polymorphism can exert its power. So, if an abstract class has no fields and all methods are abstract methods, we can rewrite the abstract class into an interface!

5. Advantages

According to the concept and characteristics of the interface, the interface has the following advantages:

  • The interface can reduce the coupling of the program;
  • Interfaces allow for more natural use of polymorphism;
  • Interface design and implementation are completely separated;
  • Using the interface makes it easier to build a program framework.

6. Companion video

The video links accompanying this section are as follows:

player.bilibili.com/player.html…

2. Definition and implementation of interface

1. Interface definition

1.1 Basic syntax

When we use interface to define an interface, the basic grammatical format is as follows:

访问修饰符 interface 接口名称 [extends] [接口名1, 接口名2,...] {
    // 声明变量
    // 抽象方法
    // 默认实现
}
复制代码

We should note that because the interface is implicitly abstract by default, it is not necessary to use the abstract keyword when declaring the interface. Each method and variable in the interface is also implicitly abstract and public by default, and the abstract and public keywords are also not required when declaring. Another interface can also use the extends keyword to inherit several other interfaces. But we must note that interface inheritance is not single inheritance, that is, an interface can inherit multiple other interfaces! ! ! When inheriting multiple interfaces, separate them with commas. As shown below:

 

1.2 Implementation Case

/** 
 * @author 一一哥Sun
 * 千锋教育
 * 飞行能力
 */
public interface Flyable {
    //接口中的方法,默认都是公开的抽象方法,不用加public和abstract关键字,也不用有方法体
    void fly();

    //JDK 8开始,接口中允许有默认的方法实现,该方法可以带public,也可以不带,但是不能是private修饰的
    public default void flyInDream() {
	System.out.println("在梦中,我可以飞");
    };
	
    //JDK 9开始,接口中允许有private修饰的私有方法,但是该方法必须有实现的方法体
    private void flyWithMe() {
	System.out.println("跟我一起飞");
    };
}
复制代码

From the above code, it can be verified that the methods in the interface are all public abstract methods by default, and there is no need to add public and abstract keywords, and there is no need to have a method body. Starting from JDK 8, the default method implementation is allowed in the interface. The method can be modified with public or not, but it cannot be modified with private. Starting from JDK 9, private methods are allowed in interfaces, but the method must have an implemented method body. Of course, under normal circumstances, neither the default implementation method nor the private method in the interface is necessary, but the public abstract method is necessary.

2. Interface implementation

After an interface is defined, we can implement the interface. At this time, we need to use the implements keyword.

/**
 * @author 一一哥Sun
 * 千锋教育
 * 人类可以继承动物类,同时还可以通过实现若干个接口来扩展自己的能力。
 * 实现接口必须接口里的抽象方法。
 */
public class Person implements Flyable{
    @Override
    public void fly() {
	System.out.println("人可以坐飞机飞行");
    }
}
复制代码

A class can implement multiple interfaces at the same time. When implementing multiple interfaces, the interface names must be separated by commas.

3. Interface inheritance

In Java, interfaces can be inherited, that is, one interface can inherit another interface. Similar to the inheritance method of classes, the inheritance of interfaces also uses the extends keyword, and sub-interfaces can inherit the methods in the parent interface. But unlike class inheritance, interfaces can have multiple inheritance.

3.1 Define the Skill interface

/**
 * @author 一一哥Sun
 * 千锋教育
 * 技能接口
 */
public interface Skill {
    //通用、常规技能
    void commonSkill();
}
复制代码

3.2 Inheritance interface

Interfaces allow multiple inheritance, that is, one interface can inherit another N interfaces at the same time, and the interface names are separated by commas.

/**
 * @author 一一哥Sun
 * 千锋教育
 * 飞行能力
 */
public interface Swingable extends Skill{
    //游泳
    void swing();
}
复制代码

3.3 Implement multiple interfaces

If we define an A interface, there are 2 methods in the A interface; then define a B interface, there are 3 methods in the B interface; then let the A interface inherit the B interface, at this time, when the C class implements the A interface At the time, 5 methods need to be implemented, because class C needs to implement all the abstract methods in the inheritance tree. Let's look at the following case:

/**
 * @author 一一哥Sun
 * 千锋教育
 * 一个类可以实现多个类
 */
public class Student implements Flyable,Swingable{
    //该方法来自于Skill接口,Swingable接口继承了Skill接口
    @Override
    public void commonSkill() {
	System.out.println("学会了常规技能操作");
    }

    //该方法来自于Swingable接口
    @Override
    public void swing() {
	System.out.println("学会了游泳技能操作");
    }

    //该方法来自于Flyable接口
    @Override
    public void fly() {
	System.out.println("学会了飞行技能操作");
    }
}
复制代码

But we should pay attention, when we want to rewrite the method declared in the interface, we need to pay attention to the following rules:

  • When a class implements a method in an interface, it cannot throw a mandatory exception. It can only throw the mandatory exception in the interface or an abstract class that inherits the interface;
  • A class must maintain a consistent method name when rewriting methods, and the two should maintain the same or compatible return value types;
  • If an abstract class implements an interface, it is not necessary for the class to implement the methods in the interface.

4. Companion video

The video link accompanying this article is as follows:

player.bilibili.com/player.html…

3. Marker interface

1. Concept

In addition to the conventional common interface above, there is actually a more "personal" interface in Java, which is the "marker interface". The so-called marker interface refers to the interface without any methods and properties. This interface is mainly used to indicate that all classes that implement this interface belong to a specific type, which can be tested by other codes to allow some operations to be performed. Any class that implements the marker interface is equivalent to putting a stamp on everyone's body and putting a mark on it, indicating that everyone is "one type of person" and "all the way".

The most common marker interface in Java is the Serializable serialization interface, as shown in the following figure:

 

The Serializable interface can make all classes that implement this interface have the ability to be serialized:

Serializability of a class is enabled by the class implementing the java.io.Serializable interface.

2. Function

The existence of the marker interface mainly has two functions:

  • Create a public parent interface: If our project is very complicated, there are multiple or even dozens of classes or interfaces that are actually the same type, we can use a marker interface as the parent interface of a group of interfaces, just to find one for everyone The common "father".
  • Giving data types to classes through polymorphism: Although a class that implements a marker interface does not need to implement any interface methods, we can use polymorphism to turn the class into an interface type.

4. New features of the interface

1. New features

Brother Yi told everyone before that Java is a language that is constantly updated and iterated. Now there will be a major version iteration of the JDK every six months, and some new features will appear after each iteration. Of course, when updating, not all technologies are updated, but the original technologies that are not so efficient or safe are upgraded. For example, in different JDK versions, there are different upgrades to the interface:

  • After JDK 8, there can be static methods and method bodies in the interface;
  • After JDK 8, interfaces are allowed to contain methods with specific implementations, which are called default "default methods". Default methods are decorated with the default keyword.
  • After JDK 9, the method is allowed to be defined as private in the interface, so that some reused code will not expose the method.

2. Example code

/**
 * @author 一一哥Sun
 * 千锋教育
 * 飞行能力
 */
public interface Flyable {
    //接口中的方法,默认都是公开的抽象方法,不用加public和abstract关键字,也不用有方法体
    void fly();

    //JDK 8开始,接口中允许有默认的方法实现,该方法可以带public,也可以不带,但是不能是private修饰的
    public default void flyInDream() {
	System.out.println("在梦中,我可以飞");
    };
	
    //JDK 9开始,接口中允许有private修饰的私有方法,但是该方法必须有实现的方法体
    private void flyWithMe() {
	System.out.println("跟我一起飞");
    };
}
复制代码

Everyone should note that for the default default method, its purpose is that when we need to add a method to the interface, all subclasses need to be modified and implemented accordingly. But if the newly added method is the default method, then the subclass does not have to modify all of it, it only needs to rewrite the newly added method where it needs to be overridden, because the implementation class does not need to rewrite the default method.

------------------------------ The feature film is over, let's smoke afterwards ------------ ----------------

4. Conclusion

So far, Brother Yi has explained the basic usage and characteristics of the interface to everyone. Finally, let’s summarize the key points of this article:

  • Interfaces are divided into narrow and broad interfaces;
  • Interface is also a data type, suitable for up-casting and down-casting;
  • All methods in the interface are abstract methods, and instance fields cannot be defined in the interface;
  • To clarify the difference between interface and class, abstract class;
  • A class can only inherit from one class, but can implement multiple interfaces;
  • An interface can inherit multiple other interfaces;
  • In general, every method in an interface is implicitly abstract ;
  • There can be variables in the interface, which will become constants by default ;
  • Before JDK 8, the methods in the interface were not implemented by default ;
  • Starting from JDK 9, methods are allowed to be defined as private in interfaces ;

Guess you like

Origin blog.csdn.net/a1014981613/article/details/130286100