Search code examples
javaclasspublicmembers

Public class requires public members (when accessing members)?


I noticed in my Java book, in the section about packages and the private modifier, that the code redundantly used private on the class and the members of the class being accessed outside of the package.

package bookpack;

public class Book {
    private String title;
    private String author;
    private int pubDate;

    public Book(String t, String a, int d) {
        title = t;
        author = a;
        pubDate = d;
    }

    public void show() {
        System.out.println(title);
        System.out.println(author);
        System.out.println(pubDate + "\n"); 
    }
}

When I remove the public from show(), Eclipse gives an error stating that the member cannot be accessed (when attempting to do so from another package). I understand that it is because it is not public and therefore cannot be accessed from outside the package. However, since the class is public, I thought that all members of the class would then be public, unless otherwise specified. That would follow the "general specifications here, specific specifications later" style, similar to inheritance. Much like how you cannot call a dynamic object from a static method. So why is the public tag required on the member of a public class? How does a public tag affect accessibility in the context of retrieving a public member of a class


Solution

  • Expanded from the comments section

    Access modifiers only apply to the things they directly modify. Thus, public on a class only affects the visibility of the class -- not the visibility of any of its members. Thus, you can provide public members for a package-private class, which could be useful if you have an abstract class you want to keep hidden from the public API.

    In addition, the lack of a visibility modifier is already defined to mean package-private visibility. Thus, it cannot be used to mean "same as class". As for why the language is designed that way, the best I could come up with is that it might have seemed like a good balance between limiting visibility to the outside world while still allowing different top-level classes to interact.