186

I have two packages in my project: odp.proj and odp.proj.test. There are certain methods that I want to be visible only to the classes in these two packages. How can I do this?

If there is no concept of a subpackage in Java, is there any way around this? I have certain methods that I want to be available only to testers and other members of that package. Should I just throw everything into the same package? Use extensive reflection?

4
  • stackoverflow.com/questions/2388253/…
    – Abdull
    Commented Jan 10, 2013 at 18:47
  • 2
    As an aside, tests should only ever test the behavior of your objects as observable from outside the package. Accessing package-scope methods/classes from your tests tells me the tests are probably testing implementations not behaviors. Using a build tool like maven or gradle, they will make it easy for your tests to run in the same classpath but not be included in the final jar (a good thing), thus no need for them to have different package names. Yet putting them in separate packages anyways is to enforce that you do not access private/default scope and thus test only the public api.
    – derekv
    Commented Jul 24, 2015 at 16:04
  • 3
    This may be true if you are working in a purely behaviour driven manner and want your tests to only do black box testing. But there can be cases where the implementation of the desired behaviour requires an unavoidably high cyclomatic complexity. In this case it can be nice to break the implementation down into smaller, simpler chunks (still private to the implementation) and write some unit tests to perform white box testing on the different paths through these chunks. Commented Sep 23, 2016 at 8:50

9 Answers 9

194

You can't. In Java there is no concept of a subpackage, so odp.proj and odp.proj.test are completely separate packages.

2
  • 13
    Although I like it this way, it's confusing that most IDEs put packages with the same name together. Thanks for clarification. Commented May 26, 2016 at 21:39
  • 2
    This is not strictly accurate: the JLS does define subpackages, though the only language significance they have is to prohibit "against a package having a subpackage with the same simple name as a top level type". I have just added an answer to this question explaining this in detail.
    – M. Justin
    Commented Jan 28, 2020 at 20:45
64

The names of your packages hint that the application here is for unit testing. The typical pattern used is to put the classes you wish to test and the unit test code in the same package (in your case odp.proj) but in different source trees. So you would put your classes in src/odp/proj and your test code in test/odp/proj.

Java does have the "package" access modifier which is the default access modifier when none is specified (ie. you don't specify public, private or protected). With the "package" access modifier, only classes in odp.proj will have access to the methods. But keep in mind that in Java, the access modifiers cannot be relied upon to enforce access rules because with reflection, any access is possible. Access modifiers are merely suggestive (unless a restrictive security manager is present).

1
  • In the Maven and Gradle build tools, the standard locations for the application & test Java code are src/main/java & src/test/java. For this specific example, the directory locations would be: src/main/java/odp/proj & src/test/java/odp/proj.
    – M. Justin
    Commented Mar 23, 2022 at 17:36
25

It is incorrect to say that there is no such thing as a subpackage in Java. The term is defined in the Java Language Specification (JLS) and has been since the initial version of the specification.

That said, there is no difference in accessibility for a member in a subpackage vs. one in an arbitrary unrelated package.

There is therefore no way within the language to make a method visible to two different packages in the requested manner, while restricting its access from other packages.

Subpackages

Java 15 JLS:

The members of a package are its subpackages and all the top level class types and top level interface types declared in all the compilation units of the package.

For example, in the Java SE Platform API:

  • The package java has subpackages awt, applet, io, lang, net, and util, but no compilation units.
  • The package java.awt has a subpackage named image, as well as a number of compilation units containing declarations of class and interface types.

The subpackage concept has practical implications, as it enforces naming constraints between packages and classes/interfaces:

A package may not contain two members of the same name, or a compile-time error results.

Here are some examples:

  • Because the package java.awt has a subpackage image, it cannot (and does not) contain a declaration of a class or interface type named image.
  • If there is a package named mouse and a member type Button in that package (which then might be referred to as mouse.Button), then there cannot be any package with the fully qualified name mouse.Button or mouse.Button.Click.
  • If com.nighthacks.java.jag is the fully qualified name of a type, then there cannot be any package whose fully qualified name is either com.nighthacks.java.jag or com.nighthacks.java.jag.scrabble.

However, this naming restriction is the only significance afforded to subpackages by the language:

The hierarchical naming structure for packages is intended to be convenient for organizing related packages in a conventional manner, but has no significance in itself other than the prohibition against a package having a subpackage with the same simple name as a top level type declared in that package.

For example, there is no special access relationship between a package named oliver and another package named oliver.twist, or between packages named evelyn.wood and evelyn.waugh. That is, the code in a package named oliver.twist has no better access to the types declared within package oliver than code in any other package.

Solutions

Since subpackages provide no special access relationship, there is no way within the language to make a method visible to two different packages in the requested manner, while restricting its access from other packages.

Either the method can be made public and all packages (including odp.proj and odp.proj.test) will be able to access the given methods, or the method could be made package private (the default visibility), and all the code that needs to directly access it must reside in the same (sub)package as the method.

Regarding the test use case, a standard practice in Java is to put the test code for a type in the same package as its source code, but in a different location on the file system. For instance, in both the Maven and Gradle build tools, the convention would be to put the source files in src/main/java/odp/proj and the test files in src/test/java/odp/proj. When compiled by the build tool, the items in both directories end up in the odp.proj package, but only the src files are included in the production artifact; the test files are only used at build time to verify the production files. With this setup, test code can freely access any package private or protected code of the code it's testing, as they will be in the same package.

In the case where you want code sharing across subpackages or sibling packages that isn't the test/production case, one solution I've seen some libraries use is to put that shared code as public, but document that it is intended for internal library use only.

12

This is no special relation between odp.proj and odp.proj.test - they just happen to be named as apparently related.

If the odp.proj.test package is simply providing tests then you can use the same package name (odp.proj). IDEs like Eclipse and Netbeans will create separate folders (src/main/java/odp/proj and src/test/java/odp/proj) with the same package name but with JUnit semantics.

Note that these IDEs will generate tests for methods in odp.proj and create the appropriate folder for the test methods it doesn't exist.

1
  • To be precise, there technically is a relation between odp.proj and odp.proj.test: a subpackage relation (see stackoverflow.com/a/59956720/1108305). But this are correct that there is no special access relation between the two — just the minimal naming restrictions that come with the subpackage relation.
    – M. Justin
    Commented Jul 9 at 15:43
5

When I do this in IntelliJ, my source tree looks like this:

src         // source root
- odp
   - proj   // .java source here
- test      // test root
  - odp
     - proj // JUnit or TestNG source here
5

As others have explained, there is no such thing as a "subpackage" in Java: all packages are isolated and inherit nothing from their parents.

An easy way to access protected class members from another package is to extend the class and override the members.

For instance, to access ClassInA in package a.b:

package a;

public class ClassInA{
    private final String data;

    public ClassInA(String data){ this.data = data; }

    public String getData(){ return data; }

    protected byte[] getDataAsBytes(){ return data.getBytes(); }

    protected char[] getDataAsChars(){ return data.toCharArray(); }
}

make a class in that package that overrides the methods you need in ClassInA:

package a.b;

import a.ClassInA;

public class ClassInAInB extends ClassInA{
    ClassInAInB(String data){ super(data); }

    @Override
    protected byte[] getDataAsBytes(){ return super.getDataAsBytes(); }
}

That lets you use the overriding class in place of the class in the other package:

package a.b;

import java.util.Arrays;

import a.ClassInA;

public class Driver{
    public static void main(String[] args){
        ClassInA classInA = new ClassInA("string");
        System.out.println(classInA.getData());
        // Will fail: getDataAsBytes() has protected access in a.ClassInA
        System.out.println(Arrays.toString(classInA.getDataAsBytes()));

        ClassInAInB classInAInB = new ClassInAInB("string");
        System.out.println(classInAInB.getData());
        // Works: getDataAsBytes() is now accessible
        System.out.println(Arrays.toString(classInAInB.getDataAsBytes()));
    }
}

Note that this only works for protected members, which are visible to extending classes (inheritance), and not package-private members which are visible only to sub/extending classes within the same package. Hopefully this helps someone!

4

EDIT: If there is no concept of a subpackage in Java, is there any way around this? I have certain methods that I want to be available only to testers and other members of that package.

It probably depends a bit on your motives for not displaying them but if the only reason is that you don't want to pollute the public interface with the things intended only for testing (or some other internal thing) I would put the methods in a separate public interface and have the consumers of the "hidden" methods use that interface. It will not stop others from using the interface but I see no reason why you should.

For unit tests, and if it is possible without rewriting the lot, follow the suggestions to use the same package.

0

Without putting the access modifier in front of the method you say that it is package private.
Look at the following example.

package odp.proj;
public class A
{
    void launchA() { }
}

package odp.proj.test;
public class B
{
    void launchB() { }
}

public class Test
{
    public void test()
    {
        A a = new A();
        a.launchA()    // cannot call launchA because it is not visible
    }
}
0

With the PackageVisibleHelper class, and keep it private before PackageVisibleHelperFactory frozen, we can invoke the launchA(by PackageVisibleHelper ) method in anywhere:)

package odp.proj;
public class A
 {
    void launchA() { }
}

public class PackageVisibleHelper {

    private final PackageVisibleHelperFactory factory;

    public PackageVisibleHelper(PackageVisibleHelperFactory factory) {
        super();
        this.factory = factory;
    }

    public void launchA(A a) {
        if (factory == PackageVisibleHelperFactory.INSTNACNE && !factory.isSampleHelper(this)) {
            throw new IllegalAccessError("wrong PackageVisibleHelper ");
        }
        a.launchA();
    }
}


public class PackageVisibleHelperFactory {

    public static final PackageVisibleHelperFactory INSTNACNE = new PackageVisibleHelperFactory();

    private static final PackageVisibleHelper HELPER = new PackageVisibleHelper(INSTNACNE);

    private PackageVisibleHelperFactory() {
        super();
    }

    private boolean frozened;

    public PackageVisibleHelper getHelperBeforeFrozen() {
        if (frozened) {
            throw new IllegalAccessError("please invoke before frozen!");
        }
        return HELPER;
    }

    public void frozen() {
        frozened = true;
    }

    public boolean isSampleHelper(PackageVisibleHelper helper) {
        return HELPER.equals(helper);
    }
}
package odp.proj.test;

import odp.proj.A;
import odp.proj.PackageVisibleHelper;
import odp.proj.PackageVisibleHelperFactory;

public class Test {

    public static void main(String[] args) {

        final PackageVisibleHelper helper = PackageVisibleHelperFactory.INSTNACNE.getHelperBeforeFrozen();
        PackageVisibleHelperFactory.INSTNACNE.frozen();


        A a = new A();
        helper.launchA(a);

        // illegal access       
        new PackageVisibleHelper(PackageVisibleHelperFactory.INSTNACNE).launchA(a); 
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.