INTERFACE
Defining an Interface, Implementing Interfaces,Accessing Implementations Through Interface References,Partial Implementations
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.
The general form is as shown below:
access interface name
{
type final-varname1 = value;
type final-varname1 = value;
type final-varname2 = value;
….
….
type final-varnameN = value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
…..
…..
…..
return-type method-nameN(parameter-list);
}
To implement an interface use implements clause, with the class definition and implement all the methods defined by the interface, with in the class.While implementing the methods of the interface, with in the class, use public as the access specifier. Also the type signature's should also match, as specified in the interface definition.
The general form of a class that implements an interface is as shown below:
access class classname [extends superclass][ implements interface1[,interface2…]]
{
//class-body
}
}
Implementing Interface
The general form of a class that implements an interface is as shown below:
access class classname [extends superclass][ implements interface1[,interface2…]]
{
//class-body
}
Accessing Implementations Through Interface Reference
One declare variables as object references that use an interface rather than a class type
//The following example calls the callback() method via an interface reference variable:
class TestIface
{
publish static void main9String args[])
{
Callback c=new Client();
c.callback(42);
}
}
Output:
callback called with 42
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract.
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends.
The general form is shown as below:
{
//methods declaration
}
Example:
//one interface can extend another.
interface A
{
void meth1();
void meth();
}
//B now includes meth1() and meth2()....it adds meth3().
interface B extends A
{
void meth3();
}
//This class must implement all of A and B
class MyClass implements B
{
public void meth1()
{
System.out.println("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class IFExtend
{
public static void main9string args[])
{
MyClass ob=new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
No comments :
Post a Comment