One of my colleagues told me that implementing interfaces introduces overhead. Is this true?
I am not concerned about micro optimizations; I just want to know the deeper details this entails.
An implementation of an interface is a Java program that references the interface using the implements keyword. The program is required to provide method logic for all non-default methods. Optionally, the program can provide an implementation of a default method defined in the interface.
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. A class uses the implements keyword to implement an interface.
Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.
To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
couldn't resist and tested it and it looks like almost no overhead.
Participants are:
Interface IFoo defining a method
class Foo: IFoo implements IFoo
class Bar implements the same method as Foo, but no interface involved
so i defined
Foo realfoo = new Foo();
IFoo ifoo = new Foo();
Bar bar = new Bar();
and called the method, which does 20 string concatenations, 10,000,000 times on each variable.
realfoo: 723 Milliseconds
ifoo: 732 Milliseconds
bar: 728 Milliseconds
If the method does nothing, the actual calls stand out a bit more.
realfoo: 48 Milliseconds
ifoo: 62 Milliseconds
bar: 49 Milliseconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With