在Java中实现接口方法时,能否更改访问修饰符(从public)?
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP