function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Thangamani Nachimuthu 6Thangamani Nachimuthu 6 

Static method cannot be referenced from a non static context: String

Hi I am trying to write a Apex class to create an account and return the record name and i am getting the below error:
Static method cannot be referenced from a non static context: String
Here is my Code:
public class AccountHandler {
      public static String insertNewAccount(String strNames)
      {
          try
          {
          Account acct = new Account();
            acct.Name = strNames;
            acct.Phone = '(415)555-1212';
            acct.NumberOfEmployees = 100;
        insert acct;
        ID acctID = acct.Id;
// Display this ID in the debug log
System.debug('ID = ' + acctID);
              return strNames;
          }
          catch(Exception ex)
          {
              return 'NULL';
          }
      }

}
Best Answer chosen by Thangamani Nachimuthu 6
GovindarajGovindaraj
Hi Thangamani,

As this is a static method so we don't need to create an object for this class.

Instead we can execute like below,
string accountName = AccountHandler.insertNewAccount('test account');

Please let us know if this helps.

Thanks,
Govindaraj.S

All Answers

SarvaniSarvani
Hi Thangamani,

Your code looks fine. Hope your executing correctly. You will see this error if you try to execute by (Instantiate the class) like below:
AccountHandler Acc= new AccountHandler();
Acc.insertNewAccount('Testing Account');

As your method is already declared as static you don't need to instantiate the class. ​​​​​​​Try calling it like below: in your Execute anyonymus window:  ClassName.MethodName()
AccountHandler.insertNewAccount('Testing Account');

Hope this helps! Please mark as best if it does.

Thanks
GovindarajGovindaraj
Hi Thangamani,

As this is a static method so we don't need to create an object for this class.

Instead we can execute like below,
string accountName = AccountHandler.insertNewAccount('test account');

Please let us know if this helps.

Thanks,
Govindaraj.S
This was selected as the best answer
Thangamani Nachimuthu 6Thangamani Nachimuthu 6
Hi Govind,
 Thanks for your response.I am able to execute the way you had given..