How can I access non public fields of non public class in other package?
I have below non public class and I want to call getString from a class in other package. How do I do that?
class ABC{
String getString(){
return "ABC"
}
}
How can I access non public fields of non public class in other package?
I have below non public class and I want to call getString from a class in other package. How do I do that?
class ABC{
String getString(){
return "ABC"
}
}
This is what we call access-level
in Java.
The documentation is actually pretty great and you can find it here. See the table below (Copied from documentation).
public
, private
, <no modiefier>
and protected
.class
, subclass
, etc..)+--------------------------------------------------+
| Modifier | Class | Package | Subclass | World |
|-------------|-------|---------|----------|-------|
| public | Y | Y | Y | Y |
|-------------|-------|---------|----------|-------|
| protected | Y | Y | Y | N |
|-------------|-------|---------|----------|-------|
| no modifier | Y | Y | N | N |
|-------------|-------|---------|----------|-------|
| private | Y | N | N | N |
+--------------------------------------------------+
It's actually a pretty interesting fact, that by adding no modifier your code is actually more secure (isolated from the 'world') than with the
protected
modifier.
To make a class (or a method) hidden from the rest of the world, apart from its own package, you give it no modifier. Like I showcase below with class ABC
.
One possible solution, is to create another class, in that same package that can access only the fields you want the rest of the world to see.
package myPackage;
class ABC{
//implementation
}
package myPackage;
public class XYZ{
/**
*@return This method will invoke the getString() method in class ABC
*/
public String getString(){
return ABC.getString();//supposing that getString() is static
}
}
package different_package;
import myPackage.*;
public class Main{
//You could also do: 'myPackage.XYZ <variable name>'
XYZ xyzInstance= new XYZ();
/*some code*/
// Accesses the method you want
xyzInstance.getString();
}