Академический Документы
Профессиональный Документы
Культура Документы
Interface defines what a class must do but not how it will do it.
In java, an interface defines set of methods that will be implemented by a class.
interfaces are similar to abstract classes, except that no method can include a
body.
an interface is a construct that describes functionality without specifying
implementation.
An interface is declared by use of the interface keyword.
access interface name {
ret-type method-name1(parameter-list);
ret-type method-name2(parameter-list);
|
|
ret-type method-nameN(parameter-list);
}
access -> either public or not used (because it makes them accessible to the
widest range of code).
In an interface, methods are declared using only their return type and signature.
They are essentially abstract methods.
once an interface is defined, any number of classes can implement it. This
makes it possible for 2 or more classes to provide the same functionality even
though they might do so in different ways.
To implement an interface, follow these 2 steps:
NOTE: To implement more than one interface, the interfaces are separated
with a comma.
//save as demo2.java
class twotable implements series {
int s=0;
public int getseries() {
s += 2; return s;
}
}
class threetable implements series {
int s=0;
public void show() { System.out.println("we are in threetable class"): }
public int getseries() {
s += 3; return s;
}
}
class demo2 {
public static void main(String[] s)
{
twotable ob1 = new twotable();
threetable ob2 = new threetable();
for (int i=1; i<=10;i++)
System.out.println("2 X "+i+" = "+ ob1.getseries());
ob2.show();
for (int i=1; i<=10;i++)
System.out.println("3 X "+i+" = "+ ob2.getseries());
}
}
one class can implement any number of interfaces. This makes it possible for a
single class to provide a wide range of well- defined functionality.( multiple
interfaces)
Example
interface x {
void show1();
}
interface y
{ void show2(); }
NESTED INTERFACE
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstractmethods.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and non- Interface has only static and final variables.
static variables.
4) Abstract class can have static methods, main method Interface can't have static methods, main method or
and constructor. constructor.
5) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }