Java: How to limit access of a method to a specific class?

Viewed 14302

Here's an example:

class A 
{
   List l = new List ();
   list.insert("x");
}

class List
{
   ...
   public void insert ()
   {
      /*insertion occurs*/
   }
   ...
}

Is it possible at all to keep the insert() method public, but limit access only to class A so that no other class can access it, only when called from A?

8 Answers

Yes, you can pass calling object as an argument and put a check in insert() method before actual code.

  public void insert(Object obj){
    if(obj instanceof A){
      //your code block
    }
  }

Please note that this will allow all the classes that extends A as well to call insert. If you want to restrict only for class A, add additional check.

  public void insert(Object obj){
    if((obj instanceof A) && obj.getClass().getSimpleName().equals("A")){
      //your code block
    }
  }

we can also achieve second case with only condition "obj.getClass().getSimpleName().equals("A")" as well.

Related