为什么Interface不能有受保护的方法 [英] Why Interface cannot have protected methods

查看:171
本文介绍了为什么Interface不能有受保护的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

受保护的接口

在Java中我为何无法在接口中使用受保护的方法?

In Java why cant I have protected methods in an interface?

因为根据Java规范


受保护的访问权限(由关键字表示) protected) - 同一个包中的任何类型都可访问的字段或方法,以及任何包中的子类。

protected access (denoted by the keyword protected) - a field or method accessible to any type in the same package, and to subclasses in any package.

如果有的话必须使用接口,我将实现它并覆盖方法。
因此,如果我要实现类可以访问这些方法的位置,那么可以在任何包中访问该方法。那么在接口中将方法声明为受保护的危害是什么?

If at all I have to use the interface, I am going to implement it and override the methods. So if I am going to implement where the class has access to those methods, since method accessible to in any package. So whats the harm in declaring the method as protected in Interface ?

推荐答案

受保护的方法用于共享实现 with subclasses。就实现共享而言,接口没有任何提供,因为它们根本没有实现。因此,接口上的所有方法都必须是公共的。

Protected methods are intended for sharing implementation with subclasses. Interfaces have nothing to offer as far as implementation sharing goes, because they have no implementation at all. Therefore all methods on interfaces must be public.

这篇关于为什么Interface不能有受保护的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆