With Sharing – Enforce the sharing rules that apply to current user.
Without Sharing – Doesn’t enforce the sharing rules.
If a class is not declared as either with or without sharing, the current sharing rules remain in effect. This means that if the class is called by a class that has sharing enforced, then sharing is enforced for the called class.
public with sharing class CWith
{
// All code in this class operates with enforced sharing rules.
Account a = [SELECT . . . ];
public void m()
{
. . .
}
}
public without sharing class CWithout
{
// All code in this class ignores sharing rules and operates
// as if the context user has the Modify All Data permission.
public void m()
{
. . .
// This call into CWith operates with enforced sharing rules
// for the context user. When the call finishes, the code execution
// returns to without sharing mode.
CWith.m();
}
public class CInner
{
// All code in this class executes with the same sharing context
// as the code that calls it.
// Inner classes are separate from outer classes.
. . .
// Again, this call into CWith operates with enforced sharing rules
// for the context user, regardless of the class that initially called this inner class.
// When the call finishes, the code execution returns to the sharing mode that was used to call this inner class.
CWith.m();
}
public class CInnerWithOut exends CWithout
{
// All code in this class ignores sharing rules because
// this class extends a parent class that ignores sharing rules.
}
}