The best and most useful answer depends on the context of the question, which, in my opinion, is not completely obvious.
If the question was a beginner, the question of the alleged meaning of the particular, then the answer "no" is completely appropriate. I.e:
- private members A are only available in class A
- Package-private members of A are only available inside classes in package A
- protected members of A are only available in classes in package A and subclasses A
- public members of A are available anywhere in A that is visible.
Now, if, and maybe, it can be extended (thanks to Brian :)) that the question came from a more "advanced" context, which addresses the question "I know that private funds are private, but there is a language loophole", then Well, there ’s such a loophole. This happens as follows:
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; class C { private int x = 10; private void hello() {System.out.println("Well hello there");} } public class PrivateAccessDemo { public static void main(String[] args) throws Exception { C c = new C(); List<Field> fields = Arrays.asList(C.class.getDeclaredFields()); for (Field f: fields) { f.setAccessible(true); System.out.println(f.getName() + " = " + f.get(c)); } List<Method> methods = Arrays.asList(C.class.getDeclaredMethods()); for (Method m: methods) { m.setAccessible(true); m.invoke(c); } } }
Output:
x = 10 Well hello there
Of course, this is really not what application programmers have ever done. But the fact that such a thing can be done is worth knowing, and not something that should be ignored. IMHO in any case.
source share