在 Java 中实现接口方法时,我们可以将访问说明符从 (public) 更改为其他吗?
java 8object oriented programmingprogramming更新于 2024/10/13 10:30:00
Java 中的接口是方法原型的规范。每当您需要指导程序员或制定合同来指定类型的方法和字段应该如何时,您都可以定义一个接口。
要创建此类型的对象,您需要实现此接口,为接口的所有抽象方法提供主体并获取实现类的对象。
接口的所有方法都是公共和抽象的,我们将使用 interface 关键字定义一个接口,如下所示 −
interface MyInterface{ public void display(); public void setName(String name); public void setAge(int age); }
实现接口的方法
在实现/重写方法时,子类/实现类中的方法的访问限制不得高于超类中的方法。如果您尝试这样做,则会引发编译时异常。
由于 public 是最高可见性或最低访问限制,并且接口的方法默认为 public,因此您无法更改修饰符,这样做意味着增加访问限制,这是不允许的,并会生成编译时异常。
示例
在下面的示例中,我们通过删除访问说明符"public"从接口继承方法。
interface MyInterface{ public static int num = 100; public void display(); } public class InterfaceExample implements MyInterface{ public static int num = 10000; void display() { System.out.println("This is the implementation of the display method"); } public void show() { System.out.println("This is the implementation of the show method"); } public static void main(String args[]) { MyInterface.num = 200; } }
输出
编译时错误 −
在编译时,上述程序会产生以下编译时错误。
InterfaceExample.java:7: error: display() in InterfaceExample cannot implement display() in MyInterface void display() { ^ attempting to assign weaker access privileges; was public InterfaceExample.java:14: error: cannot assign a value to final variable num MyInterface.num = 200; ^ 2 errors