3

I am working with Apex inner classes and I got the limitation described below

I can't name a method in my inner class with the same name I used in a static method in the containing class

When I do that I got this error

myClass.myInnerClass: Instance method clashes with static method: myMethod(): from: myClass

Code example

public class MyClass{
    public static void myMethod(){
        // outer myMethod code
    }

    public class MyInnerClass{
        public void myMethod(){
            // inner myMethod code
        }
    }
}

I don't understand the clashes between the two methods, because from what I know

The outer method can be called like this : MyClass.myMethod()

The inner method can be called like this : (new MyClass.MyInnerClass()).myMethod()

Do you have more info about this limitation of the language ?

3

Consider these two valid examples:

method1() is a static method on the outer class:

public class Example{
  public static void method1(){
    system.debug('static method');
  }
  public class innerClass{
    public innerClass(){
      method1();
    }
  }
}

method1() is an instance method on the inner class:

public class Example{
  public class innerClass{
    public void method1(){
      system.debug('instance method');
    }
    public innerClass(){
      method1();
    }
  }
}

When creating an instance of the inner class:

new Example.innerClass();

The class constructor works in each case, and is able to successfully call method1(), logging static method and instance method respectively.

But what if the class had both the static and instance methods with the same signature? Which method1() would be called in the constructor?

It's this ambiguity that prevents the compiler from allowing static and instance methods from having the same signature.

  • Sorry I don't get it, In my case the instance method is in the innerClass, if I want to call it from the containing class constructor I have to instantiate the innerClass so why there is clash? – benahm Mar 14 '17 at 9:02
  • Inner classes can call static methods on their containing class. I'll make that more clear in my examples. – martin Mar 14 '17 at 9:05

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.