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:
And when no sharing model is declared or inherited,
So here we have
a
,with sharing
, calling a method on the inner classb.c
, which does not declare a sharing model. Since inner classes do not inherit sharing, andb.c
has no superclass, it will acquire awith sharing
context from the calling class,a
.If, rather than being an inner class,
c
were a subclass ofb
:here,
c
would in fact be awithout sharing
class, because it inherits that declaration from its superclass - and this would apply regardless of who calledc.testing()
.