Java接口方法

有一条规则 无论您是否定义,接口的每个成员都是唯一且唯一的公共成员 因此,当我们在实现接口的类中定义接口的方法时,我们必须将其作为公共访问权限 子类无法为这些方法分配较弱的访问权限 . 根据定义,无论我们是否声明,接口中存在的每个方法都是公共的和抽象的。因此,在接口内部,以下方法声明是相等的。

null
void methodOne();
public Void methodOne();
abstract Void methodOne();
public abstract Void methodOne();

公众: 使此方法可用于每个实现类。 摘要: 实现类负责提供实现。 此外,我们不能对接口方法使用以下修饰符。

  • 私有的
  • 受保护的
  • 最终的
  • 静止的
  • 同步的
  • 出生地的
  • 严格的

// A Simple Java program to demonstrate that
// interface methods must be public in
// implementing class
interface A
{
void fun();
}
class B implements A
{
// If we change public to anything else,
// we get compiler error
public void fun()
{
System.out.println( "fun()" );
}
}
class C
{
public static void main(String[] args)
{
B b = new B();
b.fun();
}
}


输出:

fun()

如果我们在类B中将fun()改为public以外的任何值,就会出现编译器错误“试图分配较弱的访问权限;was public”

本文由 闪烁泰吉 .如果你喜欢GeekSforgek,并且想贡献自己的力量,你也可以写一篇文章,并将文章邮寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享