+ Start a Discussion
tanuja 1tanuja 1 

when to use public,private,global

Raj VakatiRaj Vakati
Private :- This is the default and means that the method or variable is accessible only within the Apex. If you do not specify an access modifier, the method or variable is private.

Protected :- This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class. You can only use this access modifier for instance methods and member variables.

Public :- This means the method or variable can be used by any Apex in this application or namespace.

global :This means the method or variable can be used by any Apex code that has access to the class, not just the Apex code in the same application. This access modifier should be used for any method that needs to be referenced outside of the application, either in the SOAP API or by other Apex code. If you declare a method or variable as global, you must also declare the class that contains it as global.


refer this link 

https://www.salesforcetutorial.com/publicprivateprotected-global-keywords-in-apex-programming/
https://salesforcelearningpoint.wordpress.com/2015/12/24/access-modifiers-in-salesforce-apex/
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_access_modifiers.htm
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_defining.htm

 
Ajay K DubediAjay K Dubedi
Hi Tanuja,

Public :
This keyword is used to Defines a class or method or variable that can
be used by any Apex in this application or namespace.

Private:
This key word is used to Defines a class/method/variable that is only
known locally, within the section of code in which it is defined. This
is the default scope for all methods and variables that do not have a
scope defined.  

Protected:
This keyword defines a method/variable that is visible to any inner
classes in the defining Apex class.

Global:
Defines a class, method, or variable that can be used by any Apex
that has access to the class, not just the Apex in the same application.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi