Java - 包私有类中的方法可访问性? [英] Java - Method accessibility inside package-private class?

查看:36
本文介绍了Java - 包私有类中的方法可访问性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包私有的java类(用类"声明,而不是公共类"),如果里面的方法声明为public或protected或package-private,真的没有区别,对吧?那么我应该使用哪个,或者我应该什么时候使用哪个?我有点糊涂了.

If I have a java class which is package-private (declared with "class", not "public class"), there is really no difference if the methods inside are declared public or protected or package-private, right? So which should I use, or when should I use which? I'm a bit confused.

推荐答案

如果我有一个包私有的java类(用类"声明,而不是公共类"),如果里面的方法声明为public、protected或package-private,真的没有区别,对吧?

If I have a java class which is package-private (declared with "class", not "public class"), there is really no difference if the methods inside are declared public or protected or package-private, right?

好吧,也许不会马上.但是,如果您当时(或将来)声明从包私有类继承的受保护"或公共"类,那么原始类成员的可见性确实很重要.

Well maybe not immediately. But if you then (or in the future) declare a 'protected' or 'public' class that inherits from the package-private class, then the visibility of the members of the original class do matter.

正如@kmccoy 指出的那样,将类声明为 final 消除了子类的可能性.

As @kmccoy points out, declaring the class as final removes the possibility of subclasses.

但这真的只是门面.如果您随后决定确实需要创建子类,您只需删除 final ... 然后您又回到访问修饰符的选择很重要的情况.

But this is really only window-dressing. If you then decide that you really need to create subclasses, you simply remove the final ... and then you are back in the situation where the choice of access modifiers does matter.

IMO,最重要的是你应该选择最合适的修饰符......即使现在没有必要.如果不出意外,您选择的修饰符应该记录您对抽象边界所在位置的意图.

IMO, the bottom line is that you should pick the most appropriate modifiers ... even if it is not necessary right now. If nothing else, your choice of modifiers should document your intent as to where the abstraction boundaries lie.

这篇关于Java - 包私有类中的方法可访问性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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