Interfaces in Java tips.
Main uses:
Provides complete abstraction defines only what class needs to be done, but not how it will do.
polymorphism : runtime it can be decided which implements class object can be called.
multiple inheritance.
Rules:
Interface can only be public and default , not private or protected.
Can extend only other interfaces.
Cannot create object of interface.
Methods:
By default all methods in are public. (from Java 8 we can have private methods also).
We cannot declare methods as final, because as final methods cannot be overriden , but class extending interface must override methods for implementation so final methods are not possible.
Methods which are overriden by interface must be public.
Concrete class implementing interface must override all interface methods.
But abstract class implementing interface need not override all interface methods.
But child class of abstract class needs to take care of implementing all abstract methods.
Variables:
By default all variables are CONSTANTS (static final).
Abstract Class | Interface |
keyword abstract | keyword interface. |
child class extends abstract | child class implements |
abstract and nonabstract methods | Only abstract methods |
extends class and interface | only extends interfaces |
Variables can be final, static , etc any | Variables are CONSTANTS. |
methods can be any | Methods by default are public (from Java 8 and higher can have private methods). |
no multiple inheritance | multiple inheritance can be achieved |
Constructor | No constructor |