[SalesForce] Sharing rules and Inner classes

If I have 2 classes, Class A and class B. Class B has an inner class called Class C. Class A calls class C. My question is whether class c enforces sharing rules or not.

Public with sharing class a{
  b newb = new b();
  b.c inner = newb.new c();
  Integer a = inner.testing();
}

Public without sharing class b{

  class c{
    public static Integer testing(){
      return 5;
    }
  }

}  

(Correct me if I am wrong) but usually wherever the method located (i.e. which class it is implemented), it uses that classes sharing rule. So it does not take into account where the method is being called from. Since Inner classes are separate to outer classes, do you need to give the sharing keyword to the inner class? Or does it use the outclass's sharing rules?

I am a little confused with sharing rules using inner classes. Any help appreciated!

Best Answer

From the documentation, two critical rules:

Inner classes do not inherit the sharing setting from their container class.

Classes inherit this setting from a parent class when one class extends or implements another.

And when no sharing model is declared or inherited,

If a class isn’t declared as either with or without sharing, the current sharing rules remain in effect. This means that the class doesn’t enforce sharing rules except if [...] the class is called by another class that has sharing enforced.

So here we have a, with sharing, calling a method on the inner class b.c, which does not declare a sharing model. Since inner classes do not inherit sharing, and b.c has no superclass, it will acquire a with sharing context from the calling class, a.

If, rather than being an inner class, c were a subclass of b:

public virtual without sharing class b {
}

public class c extends b {
    public static Integer testing() {
      return 5;
    }
}

here, c would in fact be a without sharing class, because it inherits that declaration from its superclass - and this would apply regardless of who called c.testing().

Related Topic