An
interface
in
the Java Programming language is an abstract type that is used to
specify an interface(in the generic sense of the term) that classes
must implement.
Interfaces
are declared using the
interface
keyword
,
and may only contain method signature and constant declarations
(variable declarations that are declared to be
both static
and final
).
An
interface never contain method definitions.
Interfaces
cannot be instantiated,
but rather are implemented.
A
class that implements an interface must implement all of the methods
described in the interface, or be an abstract
class. Object references in Java may be specified to be of an
interface type; in which case, they must either be null,
or be bound to an object that implements the interface.
One
benefit of using interfaces is that they simulate multiple
inheritance.
All classes in Java must have exactly one base
class,
the only exception being
java.lang.Object
(the
root class of the Java type
system);
multiple classes of classes is not allowed.
A
Java class may implement, and an interface may extend, any number of
interfaces; however an interface may not implement an interface.
Example:
Program:
interface B
{
}
interface C extends B
{
}
interface D extends B,
C {
}
interface E
{
}
class Simple implements B,
C, D {
}
public class A
{
public static void main(String[]
args) {
}
}
Which
is not possible in interface?
We
cant implement an interface with interface
interface B
{
}
interface C implements B
{
}
CTE--->Compile
Time Error
CTE:Syntax
error on token "implements", extends expected
interface B
{
public void study(){
}
}
CTE:Abstract
methods do not specify a body
Remove
method body
Program:
interface B
{
public void study();
}
class Simple implements B
{
@Override
public void study()
{
System.out.println("Hai
i am the impl for study method in interface B");
}
}
public class A
{
public static void main(String[]
args) {
B
b=new B();
}
}
Cannot
instantiate the type B
Program:
interface B
{
public void study();
}
class Simple implements B
{
}
public class A
{
public static void main(String[]
args) {
Simple
s = new Simple();
s.study();
}
}
--->the
type Simple must implement the inherited abstract method B.study()
Solution:
interface B
{
public void study();
}
class Simple implements B
{
@Override
public void study()
{
System.out.println("Hai
i am in impl for study method in interface B");
}
}
public class A
{
public static void main(String[]
args) {
Simple
s = new Simple();
s.study();
}
}
O/P:Hai
i am in impl for study method in interface B
Major
Points in interface:
possible:
interface
extends interface
interface
extends interface1,interface2
class
implements interface
class
implements interface1,interface2
interface B
{
}
interface C extends B
{
}
interface D extends B,
C {
}
interface E
{
}
class Sam implements B{
}
class Simple implements B,C{
}
public class A
{
public static void main(String[]
args) {
}
}