0

I have a package that contains two classes. Private variable share is located in class A and that variable can be accessed only by these two classes, A and B, and can't be accessed by importing the package. Is it possible to achieve this?

// A.java    
class A {
    private static String share;

}

// B.java
class B {
    public String myMethode() {
        // do something with share
    }
}
Srdjan M.
  • 3,310
  • 3
  • 13
  • 34

1 Answers1

1

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.

Vadim
  • 4,027
  • 2
  • 10
  • 26