Interface is custom type which can be defined by the user as
and when need arises.
Why and when we create
interface in java?
Uses of interface in Java.
You can define interface as a fully abstract type and even if
you do not define it as ‘abstract’ interface will be always abstract
internally.
You can declare ‘public static’ variables explicitly (by
yourself) but even if you do not define them as ‘public abstract’ the variables
inside the interface will be public abstract by default i.e. in case you do not
use any modifiers while declaring variables. Following is the list of modifiers
that can be used with variable declaration inside the interface:
·
Private.
·
Protected.
·
Transient.
·
Volatile.
When you
declare any method inside the interface then it will be ‘public abstract’ by
default. So you must terminate the method termination with semicolon (;) as it
is ‘abstract’.
But you can
define other types of methods in interface by using any of the following
methods:
·
Private.
·
Protected.
·
Final.
·
Synchronized.
·
Native.
·
Strictfp.
Inside an
interface you can not define the following blocks:
·
Constructors.
·
Instance block.
·
Static blocks.
You can
declare an inner class inside the interface but it will be ‘public static’
inner class.
You cannot
use interface directly but you must define an class which implements the
interface, the features of which you want to use. But any class which is
implementing an interface must implement all unimplemented methods which are
not implemented in interface but are declared in the interface.
You can
avoid this implementing all the methods in interface by declaring a class as
‘abstract’.
Interface
or a class can ‘implement’ any number of other interfaces but an interface cannot
‘implement’ class. In other words an interface cannot inherit the features of a
class. But either class or an interface can inherit features of one or more
interfaces.
You can
also create a variable for an interface which will be of type interface and it
can hold the reference of Objects of classes which are implementing that
particular interfaces.
There is
another special case of interface called as marker interface. Marker interface
does not have any implementation inside it and marker interface is used to
verify the condition that whether the class can perform certain tasks or not.
0 comments:
Post a Comment