After my last post about inheriting a private member (which isn't really inherited at all), I began to think about what would happen if you tried to inherit a default or package level member. This is the test I wrote:
When I do this, I can successfully compile the first file (where the child class is in the same package as the parent class), but I get a compiler error when I try to compile the second file stating that the field named i is not visible. So, am I correct is stating that members which are given no accessibility modifier (have the default accessibility) are inherited only by classes that are in the same package as the class that defines those members? This seems a little odd to me and, at the very least, seems like something that would seldom be used. Thanks, Corey
Your reasoning is correct. Default member are often used when you don't want anybody using them outside of your package. Browse through the sources of the JDK and look for yourself, you'd be amazed how many "default" accessible members you can find... It could well be the case that several classes within a package may need to use specific members of a class. Instead of making those members private and access them through getter methods (which may result in a performance penalty if the member is frequently requested because it costs more to invoke a method than to just access a member), we can ensure that only classes in the package are accessing it. BUT, this is used internally by some JDK packages because YOU, as an outside developer, cannot develop new classes for java.util (for instance), and thus, would not be able to access a "default" member of a class within the java.util package. In clear, you cannot call your package java.util since it will resault in a compile-time error. This was done to prevent that people not involved in the development of Java try to "hack" some classes in some ways. As a bottom line, you are right, I would not use a "default" member if you only want it to be accessible to your package because you cannot prevent anybody else to create a class belonging to your package, and thus, access your "default" member. I'd consider making it private then.