Using Packages to create classes and Protected Scope


Packages

package in java is used to group class and interfaces. This helps developer to avoid conflict when there are huge numbers of classes. If we use this package the classes we can create a class/interface with same name in different packages. By using packages we can import the piece of again in another class. There many built in packages in java like > 1.java.util > 2.java.lang > 3.java.io We can define our own user defined packages.


Using Packages to create classes with the same name

First Test.class

package fun.bar
public class Test {
 
}

Also Test.class in another package

package fun.bar.baz
 
public class Test {
 
}

The above is fine because the two classes exist in different packages.


Using Package Protected Scope

In Java if you don't provide an access modifier the default scope for variables is package-protected level. This means that classes can access the variables of other classes within the same package as if those variables were publicly available.

package com.example;
 
public class CustomClass {
    double customNumber;
    String customString;
 
    public CustomClass() {
        customNumber = 7.5;
        customString = "Custom Test";
    }
    // No getters or setters
}
 
package com.example;
 
public class AnotherCustomClass {
    CustomClass customObject = new CustomClass();
 
    System.out.println("Custom Number: " + customObject.customNumber);
    // Prints Custom Number: 7.5
 
    System.out.println("Custom String: " + customObject.customString);
    // Prints Custom String: Custom Test
}

This method will not work for a class in another package:

package com.anotherexample;
 
public class DifferentClass {
    CustomClass customObject = new CustomClass();
 
    System.out.println("Custom Number: " + customObject.customNumber);
    // Throws an exception
 
    System.out.println("Custom String: " + customObject.customString);
    // Throws an exception
}

Basic Programs