I'll try to be as succint as possible:
Consider the interface:
package com.stackoverflow;
public interface Printable {
void print();
}
I created an enum that implements this interface. So far so good:
public enum MyEnum implements Printable {
ERROR,
WARNING,
SUCCESS;
@Override
public void print() {
System.out.println("Printed: " +this.name());
}
}
I created a main
method with the following lines:
//OK! Prints 1
System.out.println(ERROR.getClass().getInterfaces().length);
//OK! Prints "Printable" (the name of the interface).
System.out.println(ERROR.getClass().getInterfaces()[0].getSimpleName());
Everything working as expected, right? Now to the weird part:
public enum MyEnum implements Printable {
ERROR,
WARNING{
//Notice the "@Override", that means that I'm overriding a superclass/interface method! No compiler errors!
@Override
public void print() {
System.out.println("I'm not printable anymore!");
}
},
SUCCESS;
@Override
public void print() {
System.out.println("Printed: " +this.name());
}
}
Question:
Why, do overriding the print
method makes enumInstance.getClass().getInterfaces()
not to return Printable? In the example above, I know that WARNING now is part of an anonymous class, but getInterfaces
isn't supposed to return the declared interfaces (Printable in this case)?
//OK! Prints 1
System.out.println(ERROR.getClass().getInterfaces().length);
//NOT OK! Prints 0
System.out.println(WARNING.getClass().getInterfaces().length);