You cannot achieve it directly.
There are visibility levels in Java:
public - visible from any other classes
protected - visible in all classes who extend a class
so if in Class A you have
class A {
protected String share;
}
it will be visible in class B extends A
, class C extends B
and so on...
then there is a possibility to create another class D extends A
and share
will be visible in it. Unless class A
is final, but with that you cannot have needed class B extends A
package visible
package com.foo.myclasses;
class A {
String share;
}
with that share
will be visible in all classes in the package com.foo.myclasses
So still there is a way to create a class in the same package and share
will be visible in it.
You may do a Work around to achieve that.
make private String share
in class A
create protected getShare()
(or package visible) method
and check the class like
protected String getShare() {
if (this.getClass().getName().equals("com.foo.myclasses.A") or this.getClass().getName().equals("com.foo.myclasses.B")) {
return share;
} else
{
throw new IllegalAccessException(this.getClass().getName() + " is not allowed to access share);
// or return null
}
}
But it is about access to the value of share at run time. Nothing prevents access (as above) in the code. Code will compile, but throws exception at run time.
It is what it is.