Re: How to make a Java class only visible inside the package & notvisible to other packages?

Discussion in 'Java' started by Mark Space, Apr 24, 2008.

  1. Mark Space

    Mark Space Guest

    www wrote:

    > By trying different keywords,
    > final class Person
    > {

    Yeah, what they said. Make a class package private by using no keyword
    at all.

    "class Person {"

    is what you want.

    > ...//code omitted
    > public String getName(){...}
    > }
    > This solution has a problem, because I cannot extend Person anymore.

    Get rid of the final.

    > Another question is: since Person is declared as "final" and is only
    > visible inside the package, then all the "public" methods inside Person
    > is not "public" anymore, they equal to "protected" methods, correct?


    public interface People {
    String getName();

    public class PeopleProxy {
    static public People getPeople() { return new Person(); }

    class Person implements People {
    String name;
    public String getName() {return name;};

    Now, Person is package private, but getName can be accessed through the
    public interface People. I think. :) I didn't try it, but private
    classes can be exported this way (Iterator is popular) so I think this
    will work.
    Mark Space, Apr 24, 2008
    1. Advertisements

  2. Mark Space

    Mark Space Guest

    www wrote:

    > oou all. I have taken Mark Space's idea and played on Eclipse. He
    > is right.

    Not too bad for just making stuff up. ^_^

    _Learning Java_ by O'Reilly covers how this works in better detail than
    I did. It also gives a practical example how to return a private class
    of type Iterator so the user can use the public Iterator interface, but
    the details of the implementation are still encapsulated.

    I'd like you to consider reading this excellent book. It's been a big
    help to me and I think it would benefit others as well. As I've been
    helped on this list, I like to pay that help forward and try to assist
    others learning also.
    Mark Space, Apr 26, 2008
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. spamfurnace
    Scott M.
    May 24, 2004
  2. Patrick Olurotimi Ige
    Patrick Olurotimi Ige
    Jun 15, 2005
  3. beginner
    Bjoern Schliessmann
    Aug 19, 2007
  4. Jurjen de Groot
    Jurjen de Groot
    May 19, 2008