Java接口中允许的方法修饰符有哪些?
Java中的接口是方法原型的规范。每当需要指导程序员或制定一个契约,指定类型的字段和方法应该如何使用时,都可以定义一个接口。
在Java 7中
在**Java 7**中,接口的方法只能使用`public`和`abstract`作为修饰符。
interface MyInterface{
public abstract void display();
public abstract void setName(String name);
public abstract void setAge(int age);
}在接口的方法中使用任何其他修饰符都会导致编译时错误。
从Java 8开始
从**Java 8**开始,接口允许使用默认方法和静态方法。
- **静态方法** - 静态方法使用`static`关键字声明,它将与类一起加载到内存中。可以使用类名访问静态方法,无需实例化。
- 需要使用接口名称调用接口的静态方法。
示例
interface MyInterface{
public void demo();
public static void display() {
System.out.println("This is a static method");
}
}
public class InterfaceExample{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.demo();
MyInterface.display();
}
}输出
This is the implementation of the demo method This is a static method
- **默认方法** - 默认方法是接口方法的默认实现,如果接口中有默认方法,则无需在已实现此接口的类中实现它。
- 默认方法也称为防御者方法**或**虚拟扩展方法。可以使用`default`关键字定义默认方法,例如:
default void display() {
System.out.println("This is a default method");
}示例
interface sampleInterface{
public void demo();
default void display() {
System.out.println("This is a default method");
}
}
public class DefaultMethodExample implements sampleInterface{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.demo();
obj.display();
}
}输出
This is the implementation of the demo method This is a default method
从Java 9开始
从Java 9开始,接口允许使用私有方法和私有静态方法。
示例
interface MyInterface {
public abstract void demo();
public default void defaultMethod() {
privateMethod();
staticPrivateMethod();
System.out.println("This is a default method of the interface");
}
public static void staticMethod() {
staticPrivateMethod();
System.out.println("This is a static method of the interface");
}
private void privateMethod(){
System.out.println("This is a private method of the interface");
}
private static void staticPrivateMethod(){
System.out.println("This is a static private method of the interface");
}
}
public class InterfaceMethodsExample implements MyInterface {
public void demo() {
System.out.println("Implementation of the demo method");
}
public static void main(String[] args){
InterfaceMethodsExample obj = new InterfaceMethodsExample();
obj.defaultMethod();
obj.demo();
MyInterface.staticMethod();
}
}输出
This is a private method of the interface This is a static private method of the interface This is a default method of the interface Implementation of the demo method This is a static private method of the interface This is a static method of the interface
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP