Home  >  Article  >  Java  >  How to write an interface and implement it in java

How to write an interface and implement it in java

王林
王林Original
2019-11-29 11:14:595536browse

How to write an interface and implement it in java

The interface is defined as follows:

[可见度] interface 接口名称 [extends 其他的接口名] {
        // 声明变量
        // 抽象方法}

The body of the interface contains abstract methods, but all methods within the interface (by definition) are It is an abstract method, so the abstract keyword is not needed in the interface. Since an interface represents a collection of external behaviors, any method within the interface is public.

For example:

public interface Predator {
       boolean chasePrey(Prey p);
       void eatPrey(Prey p);
}

The members in the interface are all static (static), final and public (public) , conversely, they can be the type of any class or interface.

Recommended related video tutorials: java online tutorial

Implementation of interface:

public class Lion implements Predator {

        public boolean chasePrey(Prey p) {
               // programming to chase prey p (specifically for a lion)
        }

        public void eatPrey (Prey p) {
               // programming to eat prey p (specifically for a lion)
        }
}

Description:

If a class implements an interface but does not implement all the methods of the interface, it must be marked as abstract (abstract class). A subclass of an abstract class must implement its unfinished methods. If the subclass still does not implement all the methods of the interface, then the subclass still needs to be marked abstract.

Interface is usually used in the Java programming language for callback functions. Java does not allow methods to be passed as parameters. Therefore, one solution is to define an interface and use this interface as a parameter of the method to use the method signature of the object.

Sub-interface

The interface can be extended into several different interfaces, using the method described above, for example:

 public interface VenomousPredator extends Predator, Venomous {
         //介面主體
 }

above The program fragments are legally defined sub-interfaces. Unlike classes, interfaces allow multiple inheritance, and Predator and Venomous may define or inherit the same method, such as kill(Prey prey), when a class implements VenomousPredator, it will implement these two methods at the same time.

Recommended related articles and tutorials: Getting started with java

The above is the detailed content of How to write an interface and implement it in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn