1

I get this error whenever I run the below code:

Error - Only top-level class methods can be declared static

Code

public class ContactSearch 
{
    public static List<Contact> searchForContacts(String lastName, String mailCode)
    {
       return [SELECT Id, Name, LastName, MailingPostalCode 
               FROM Contact 
               WHERE LastName = :lastName AND MailingPostalCode = :mailCode];

    } 
}

Does anyone know why this is happening? I can't find the issue. I ran the accounts code the same way and it worked so I am confused with this error message.

(I tried to look for the answer in previous posts, but none applied to my case, therefore I am posing this new question.)

2

If you're declaring an inner class, all of its methods must be stateful:

public class TopLevel
{
    public class InnerClass
    {
        public List<Contact> search_WillCompile()
        {
            // this method declaration is valid
            // implementation details ommitted
        }
        public static List<Contact> search_WillNotCompile()
        {
            // this method declaration is invalid
        }
    }
}

That's in contrast to methods on a top level class, whose method declarations will compile either way:

public class TopLevel
{
    public static void staticMethod() { }
    public void statefulMethod() { }
}

If you're working within an Execute Anonymous window, all declared classes are virtual inner classes.

  • Thanks for this explanation, that cleared everything out! This might be a very silly question, but do you know how can I run the code without using the Debug> Execute Anonymous? – Ka_programmer Mar 26 '17 at 14:07
  • @Ka_programmer Depends on what you're trying to accomplish, how regularly you intend to use it, and what sort of interface you're going for. You could hook it up to a Visualforce Page for a GUI, plug it into ApexRest or a webservice to create an API, and a variety of other scenarios. – Adrian Larson Mar 26 '17 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.