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
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
}
}
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!
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