implement interface
时间: 2023-10-20 10:05:53 浏览: 47
To implement an interface in a programming language, follow these steps:
1. Define the interface: Define the methods and properties that the interface should contain.
2. Create a class that implements the interface: In the class declaration, add the keyword "implements" followed by the name of the interface. For example:
```
public class MyClass implements MyInterface {
// class code
}
```
This tells the compiler that MyClass will implement all the methods and properties defined in MyInterface.
3. Define the interface methods: Implement all the methods and properties defined in the interface. For example:
```
public class MyClass implements MyInterface {
public void method1() {
// implementation code
}
public int method2() {
// implementation code
return 0;
}
}
```
4. Use the interface: You can now use the interface to create objects of your class. For example:
```
MyInterface obj = new MyClass();
```
This creates an object of MyClass and assigns it to a variable of type MyInterface. You can then call the methods defined in the interface on the object:
```
obj.method1();
int x = obj.method2();
```