Java-Example of Package Access

Example of Package Access

If we do not specify an access control modifier, then the default is package access. If a variable or method or class has package access, then it can be accessed by all methods of classes in the same package. The package access is a good default option for classes, but this access is not preferable for variables and methods. It is better that variables are private and methods are public.

In the following program, the methods data( ) and data2( ) in the class Data will be assigned the package access by default. The data1( ) and data2( ) methods can be accessed by all methods of classes in the same package. The classes DataAccessor, DataAccessor2 and Data are assumed to be in the same package mypack. So, the methods data1( ) and data2( ) can be accessed from the methods accessData( ) and accessData2( ), which are present in the classes DataAccessor and DataAccessor2, respectively.

Program

502 final

Package Source

package mypack;

public class DataAccessor {
    
    public void accessData()
    {
        Data obj = new Data();
        obj.data1();
        DataAccessor2 obj2 = new DataAccessor2();
        obj2.accessData2();
    }
}

class DataAccessor2 {
    
    void accessData2()
    {
        Data obj = new Data();
        obj.data2();
    }
}

class Data {
    
    void data1()
    {
        System.out.println("data1 method is invoked");
    }
    void data2()
    {
        System.out.println("data2 method is invoked");
    }
}

Program Source

import mypack.DataAccessor;

public class Javaapp {
    
    public static void main(String[] args) {
        
        DataAccessor obj = new DataAccessor();
        obj.accessData();
    }
}

Leave a Comment