Java Basics  «Prev

Access Control between Packages

Classes are grouped into packages

Based on the information retrieved the Java API HTML files, all Java's classes are grouped into packages. You can group your own classes into packages.
All our Java programs will reside in the same package, which is what occurs by default.

Relating to packages

Members of a class (its variables and methods) can be accessed freely by any other class within the same package. If the member is declared as private, then it cannot be accessed freely. If you would like to make the class members accessible to code outside the package in which it is defined, you must start by declaring the class to be public.

public class VisibleToAll {
  String Visible = new String();

You can declare the members you want to access outside that package as public.
If you look through Java's API HTML files, you'll notice that the majority of Java's
  1. classes,
  2. methods, and
  3. variables

are declared as public, so that code outside the packages in which these classes, methods, and variables are defined can also access and use them.

Access Modifiers

When you declare an object type in Java (let us stick to class because it is the only one mentioned so far), you can configure who should be able to use it. Access modifiers specify access to classes, and in this case, we say that they are used at the top-level. They can also specify access to class members, and in this case, they are used at member-level.
At the top-level there are only two access modifiers that can be used: 1) public and 2) none. A top-level class that is declared public must be defined in a Java file with the same name. So, the following class is defined in a file named stored under the com.

public class Base {
  // define your member variables and methods

The contents of the class are not depicted for the moment and have been replaced with a comment. A public class is visible to all classes anywhere and a different class in a different package, can create an object of this type, like in the following sample code:

public class Main {
 public static void main(String... args) {
   // creating an object of type Base
   Base base = new Base();

For now, remember that a public class is visible to all classes everywhere.