Why java interfaces can't contain static methods implementations?
I'm just curious, wouldn't it be more convinient to allow interfaces to contain implementations of static methods? Such methods开发者_如何学Go could contain short commonly used(by this interface implementors) logic.
Because an interface describes what. It doesn't describe how.
If you really want to add (hide) some logic inside an interface, you may consider adding an inner class (Note: never do it, this just shows what is possible from a pure technical perspective):
public interface Person {
public String getFirstName();
public String getLastName();
public class Util {
public String getName(Person person) {
return person.getFirstName() + " " + person.getLastName();
}
}
}
If you use this, it "feels" a bit like having static method code in the interface:
String fullName = Person.Util.getName(this);
As I said - it's pure technically and I don't see any reason to actually do it. A static method can be located in any class, no need to add it to an interface.
An interface is a contract. It says what an implementing object will have (at minimum), but that's all. It says "this house will have a door, a window, and a chimney".
An abstract class is more like a prefab house. It's not complete (you have to add your own siding, for example) but it has parts already there (there is a space for the door, but the whole fireplace is already setup.
The problem with giving code in interfaces is multiple inheritance. Java doesn't allow it. You can have a class implement many interfaces, because interfaces only promise there will be a method with a given signature.
If interfaces held code, then you could implement 3 of them, each with a method body for myUsefulFunction(String thing)... and now you don't know which one gets called.
That's why abstract classes can have method bodys (because you can only extend one class), but interfaces can't (because you can implement multiple interfaces).
I agree that a static method doesn't make sense in an interface. But i don't understand why java allows static members in an interface. Seems a bit inconsistent.
It's the abstract class or regular class which should implement something. Interfaces are not supposed to have any implementations, but they contain the interface of communicating. So static methods are not allowed.
An interface is a special abstract class with all abstract methods.
You can feel free to create an abstract class of your own that contains (non-abstract) static methods, but then you can only inherit from one of them.
Better yet, create a separate helper class with your static methods.
精彩评论