18

As you, specialists, know in Java 8, interfaces can have static methods which have implementations inside themselves.

As I have read in a related tutorial, the classes which implement such interface can use its static methods. But, I have a problem which, here, I show it in a simpler example than what I have

public interface Interface1{
    public static void printName(){
        System.out.println("Interface1");
    }
}

when I implement such interface

public class Class1 implements Interface1{
    public void doSomeThing() {
        printName();
    }
}

I encounter compile error.

The method printName() is undefined for the type Class1

What's the problem?

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
hossayni
  • 465
  • 1
  • 3
  • 16
  • In your example you are trying to call method printName();. The compilation error you are getting is because there is no method in your class "Class1" named as printName(); and compiler is trying to find that method in your class only. โ€“ foxt7ot Dec 14 '14 at 16:35
  • 3
    *"As I have read in a related tutorial, the classes which implement such interface can use its static methods."* They can, yes -- as can classes that *don't* implement the interface. In both cases, you have to qualify the call (`Interface1.printName();`). If the tutorial suggested the above should work, though, it's simply wrong. โ€“ T.J. Crowder Dec 14 '14 at 16:53

1 Answers1

24

From the Java Language Specification,

A class C inherits from its direct superclass all concrete methods m (both static and instance) of the superclass for which all of the following are true:

  • [...]

A class C inherits from its direct superclass and direct superinterfaces all abstract and default (ยง9.4) methods m for which all of the following are true:

  • [...]

A class does not inherit static methods from its superinterfaces.

So that method is not inherited.

You can statically import the member

import static com.example.Interface1.printName;
...
printName();

or use it with the fully qualified type name

com.example.Interface1.printName();

or import the type to which printName belongs and invoke it with its short name

import static com.example.Interface1;
...
Interface1.printName();
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 15
    More generally... this reflects a (deliberate) asymmetry between the treatment of static methods in classes and in interfaces -- static methods in classes are inherited by subtypes, but static methods in interfaces are not. This was a carefully-considered decision; after all, confusion like the OPs question is the natural result of introducing such asymmetries. However, the EG strongly felt that existing inheritance of static methods in classes was essentially a design bug, and that extending it to interfaces would create many confusing multiple-inheritance corner cases for little benefit. โ€“ Brian Goetz Dec 14 '14 at 18:05