gpt4 book ai didi

java - 实现接口(interface)不起作用

转载 作者:行者123 更新时间:2023-12-01 07:26:12 25 4
gpt4 key购买 nike

public class TestImpl {
public static void main(String[] args) {
HelloImpl h1 = new HelloImpl(), h2 = h1;
h1.message = "holla";
System.out.println(h2.sayHello());
}
}

interface Hello {
String sayHello();
}

class HelloImpl implements Hello {
static String message = "Hello";

String sayHello() {
return message;
}
}

我得到“尝试分配较弱的权限。”

最佳答案

接口(interface)中,默认情况下所有成员都是公共(public)

您不能实现(或重写)方法并分配较弱的权限,因为这不允许多态性。

您必须将 sayHello() 设置为 public

class HelloImpl implements Hello {
private static final String message = "Hello";

public String sayHello() {
return message;
}
}

此外,内部常量应该是private final

关于java - 实现接口(interface)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24273196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com