简体   繁体   中英

Is a subclass always in the same package as a superclass in Java?

So there are two classes defined to be:

    public class SuperClass {
        int count = 5;
        SuperClass() {
        }

    }

    public class SubClass extends SuperClass {
        SubClass() {
            super();

    }

SubClass sub = new Subclass();
System.out.println(sub.count); // prints out 5

Unless my understanding of the default visibility modifier is wrong, I thought that the default modifier is that only classes in the same packages can access the variable count. So this implies that my SubClass is in the same package as my SuperClass but I haven't specified that they are in the same package anywhere in my code. Does this mean that a SubClass is ALWAYS in the same package as the SuperClass?

You are right: default access modifier (also called package-private ) is not accessible from a subclass if it's in another package. In your case - both classes are in the same directory which implicitly means that they are in the same package.

No, a subclass can be in a different package than its super class.

It's hard to say just from your code snippet, but I'm assuming that all of your sample code is in one file? If that's the case, then both classes will be in the same package. And if you haven't specified a package at the top of the file, then it's the "default package" that they both belong to.

If you were to separate those two classes into different files and place them in different packages, you'd find what you expect: SubClass will no longer be able to access the field defined in SuperClass .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM