2. What is an interface?
• Fully abstract class
• It is syntactically similar to class. It contains only method declaration.
• Once it is defined, any number of classes can implement an interface.
3. • A class can implement any no of interface.
•A class which implements the interface must define all methods in
interface.
• Interface supports dynamic method resolution at run time.
4. Defining an interface
Access interface interface_name
{
return-type method-name(parameter);
return-type method-name(parameter);
type final-variable-name = 10;
}
5. Main concept
• Methods are abstract by default.
• Variables are final and static by default.
• If an interface is declared as public, then method and variables
inside the interface declaration are public.
7. • Once an interface is defined, one or more class can implement it. Using the
keyword “implements”
• If a class implements more interfaces then they should be separated by
comma.
• Methods in the interface must be contained in the class. Methods used inside
the class should be defined with a keyword “public”.
• Method signature in declaration & definition must be same.
9. Class d
{
public static void main(String arg[])throws IOException
{
Demo s = new Demo();
s. display(10);
s. printDetail()
}
}
10. Class Demo implements sample
{
public void display(int x)
{
System.out.println(x);
}
}
Class Demo1 implements sample
{
public void display(int x)
{
System.out.println(“another : “ + x);
System.out.println(“===============“);
}
}
11. Class d
{
public static void main(String arg[])
{
sample s = new Demo();
Demo1 d1=new Demo1();
s. display(10); // method in demo
s=d1;
s. display(10); // method in demo1
}
}
12. Partial Implementation
• If a class doesn’t define all the methods in interface, then the class
must be declared as abstract.
13. Variable in an interface
• If we want to share constants to more classes, interface can be used.
Interface variable
Example
{
float pi=3.14;
int flag=1;
}
14. Interfaces can be extended
Interface A
{
void display();
}
Interface B extends A
{
void display2();
}
15. Conclusion
• So for now in these slides we have discussed about a small topic
named “interface”.
• Hope you get a little bit of what interface exactly is.