0

If I write ' a.m2(); ' I am getting error as ''the receiver expression should be replaced with the type qualifier 'Animal' 1 error'' . But if I write Animal.m2 I am getting proper op

interface Animal {

    void m();

    default void m1() {
        System.out.println("Hello");
    }

    static void m2() {
        System.out.println("World");
    }
}
public class Main {
    public static void main(String[] args) {
        Animal a = () -> System.out.println("Hello World");
        a.m();
        a.m1();
        //a.m2();
        Animal.m2();
    }
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
007
  • 1
  • Which compiler and Java version are you using? – MC Emperor Jun 27 '22 at 07:15
  • Hi I am using Online compiler from https://www.jdoodle.com/online-java-compiler/ – 007 Jun 27 '22 at 07:22
  • In functional interface I am getting proper op for default and abstract method . but for static method it shows error – 007 Jun 27 '22 at 07:23
  • You should not try to call a static method on an instance, as this doesn't make sense. Use the type name instead: `Animal.m2()`. The fact that it *will* work for normal classes is: history. But it's [considered a design error](https://stackoverflow.com/questions/34709082/illegal-static-interface-method-call#comment57169606_34709162). – MC Emperor Jun 27 '22 at 07:55
  • can I use lambda expression for static method as Functional interface can contains static method..? – 007 Jun 27 '22 at 10:04

1 Answers1

0

The m2() method is not an interface method, so it's not a method found on instances of Animal. It is a static method of the Animal class (which is an interface), so it needs to be qualified with the class in which it's defined, ie Animal.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • But, then it's strange that it *will* work for normal classes. This restriction only applies to interfaces. The answer seems to be: history. – MC Emperor Jun 27 '22 at 07:27
  • 1
    @MCEmperor Normal class instances have a class, so the static method may be found. The class of an implementation of an interface could be anything, and thus its class is unknown and so the static method cannot be found, both because the class is unknown but also because it's the interface class's method OP wants to refer to, not the instance's class. – Bohemian Jun 27 '22 at 08:04