What is the use of package level protection in java?

前端 未结 15 1089
时光说笑
时光说笑 2020-12-05 14:28

I know how package level protection in java works. I read a lot of code (including lots of open source stuff) and no-one seem to be using it. The whole protection l

15条回答
  •  悲哀的现实
    2020-12-05 14:55

    I know Java veterans of 5-10+ years who don't realize that protected implies package private acess. This alone, for me, makes package private an horrific language feature. Personally I don't think there is any justifiable reason to use package private anyway. Let's consider the use cases:

    • Package private classes: use inner classes. Another poster suggested there is a (small) performance penalty for inner classes vs package private classes but, to me, that's not a good reason for bad design. Package private and inner classes I consider to be implementation details and, as such, I think it's better to "hide" them as inner classes;
    • Package private data members: I can see no reason for these at all; and
    • Package private methods: these are pretty much the equivalent of C++ friend methods. C++ friends had one good raison d'etre and that was to externalize operator overloading outside of the class, which allowed the first argument to be something other than the class itself. In Java, there is no such use case, which just leaves doing an end-run around encapsulation and abstraction.

    Compare this to protected methods, which are entirely justifiable when designing classes for extension. I've seen cases where programmers inadvertently use protected methods in unrelated classes in the same package just because they come up on auto-completion lists.

    And there is absolutely no way to prevent this.

    C# has a better access system in that protected doesn't imply internal access. But I consider this--along with a mutable Date class--to be pretty huge flaws.

提交回复
热议问题