Comp 110 Visibility: public / private / package

By default, classes, instance variables, and methods are accessible to other classes in the same package and nothing else. This is called "package" visibility and it is implicit when no other modifiers are used:

package comp110;
class Cat {
  int _age;

  Cat() {
    _age = 0;
  }
  
  int getAge() {
    return _age;
  }
}

The Cat class defined above can only be instantiated by other classes in the comp110 package. 

public

What if we want code in other packages to be able to use this class? We could use the "public" visibility modifier. Using public will make the class, and the other fields/methods we declare public, visible outside of the comp110 package.

package comp110;
public class Cat {
  private int _age;
  
  public Cat() {
    _age = 0;
  }

  public int getAge() {
    return _age;
  }
}

In this case, the class, the constructor, and the getAge method are all visible and useable by classes in other packages. The instance variable _age, however, is only visible within the Cat class because we've declared it private.

private

When a method, constructor, or instance variable is declared private it means no other classes, not even classes in the same package, can "see" or make use of this variable.

When a method is declared private, it means that method cannot be called by any other classes.