Home  >  Article  >  Java  >  How to write java interface class

How to write java interface class

小老鼠
小老鼠Original
2024-01-03 15:47:35710browse

Writing method: 1. Define an interface named MyInterface; 2. Define a method named myMethod() in the MyInterface interface; 3. Create a class named MyClass and implement the MyInterface interface; 4. Create an object of the MyClass class and assign its reference to a variable of the MyInterface type.

How to write java interface class

Operating system for this tutorial: Windows 10 system, Dell G3 computer.

Java interface is an abstract type that defines a set of method contracts but does not contain the implementation of the methods. An interface is a reference type that can contain fields and methods.

To write a Java interface class, you can follow the following steps:

1. Define the interface name: The interface name should start with a capital letter and follow the camel case naming rule. For example, you can define an interface named MyInterface.

2. Define methods: Define a set of methods in the interface. These methods are abstract and have no method body or implementation. The access modifier of a method can be public or default (i.e. no modifier). For example, you can define a method named myMethod() in the MyInterface interface:

java

public interface MyInterface {  
    void myMethod();  
}

3. Implement the interface: To implement an interface, you need to create a class and add it in the class Implement all methods in the interface. Methods that implement an interface must have the same method signature as the methods in the interface. For example, you can create a class named MyClass and implement the MyInterface interface:

java

public class MyClass implements MyInterface {  
    @Override  
    public void myMethod() {  
        System.out.println("实现了MyInterface接口的myMethod方法");  
    }  
}

In the above code, the @Override annotation is used to indicate that the method overrides the one in the interface method.

4. Using an interface: To use an interface, you need to create an instance of the interface or an object that references a class that implements the interface. For example, you can create an object of the MyClass class and assign its reference to a variable of the MyInterface type:

java

MyInterface myObj = new MyClass();  
myObj.myMethod(); // 输出 "实现了MyInterface接口的myMethod方法"

In the above code, myObj is a variable of the MyInterface type, by It is assigned an object of MyClass class to use the methods in the interface.

The above is the detailed content of How to write java interface class. 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