By: Jatin Chawla
Interface Program in Java
As we know that in Java, we cannot use multiple inheritance means one class cannot be inherited from more than one classes. To use this process, Java provides an alternative approach known as “Interface”.
Java expands the concept of Abstract class with Interface means its members are not Implemented. A java class cannot be a sub class of more than one class, but a class can implements more than one Interfaces.
An Interface is usually a kind of class like classes and interface both contain methods and variables, but with a major difference i.e. Interface contain only Abstract methods and Final variable. This means that interface do not specify any code to implements these methods and data fields.
There are some points that are followed
- a. The methods in interface are “public” and “abstract” by default.
- b. The variables/Fields in interface are “public”, “static” and “final” By default.
- c. To inherit an interface to a class we use “implements” keyword.
- d. To inherit two interfaces OR two classes we use “extends” keyword.
Syntax to create an interface
<modifier> interface <interface name>
{
……………. //interface fields(By default Public, Static and Final)
……………. //interface methods(By default Public and Abstract)
}
Implementation Example of Interface
public interface First {
public void show_first();
}
public interface Second {
public void show_second();
}
public class One {
public void show_one()
{
System.out.println("Class One");
}
}
public class Two extends One implements First, Second{
public void show_first()
{
System.out.println("Interface first");
}
public void show_second()
{
System.out.println("Interface second");
}
public void show_two()
{
System.out.println("Class two");
}
}
public class DemoInterface {
public static void main(String a[])
{
Two t=new Two();
t.show_first();
t.show_second();
t.show_one();
t.show_two();
}
}
Output
Interface first
Interface second
Class One
Class two



Link to Us