View RSS Feed

My Java Tips

Interface extending Interface

Rate this Entry
by , 11-13-2011 at 12:42 PM (2126 Views)
An interface can extend other interface but cannot implement any interface. This makes sense because interface cannot have any implementation. An interface can only contain abstract methods that are implemented by the class implementing that interface.

Lets do this with an example.

Create a package named myinterfaces. Using conventions, package name should be in small case. Now create an interface named InterfaceA with 2 methods.

Java Code:
package myinterfaces; 

public interface InterfaceA {
	public void interfaceAMethod1();
	public void interfaceAMethod2();
We will now create another interface named interfaceB that will extend from interfaceA.

Java Code:
package myinterfaces;

public interface InterfaceB extends InterfaceA {
	public void interfaceBMethod1();
	public void interfaceBMethod2();

InterfaceB has two methods defined and it extends from InterfaceA.

Now lets come to the interesting point. We now will create a class that will implement interface InterfaceB.

package myinterfaces;

public class MainClass implements InterfaceB  {

	public void interfaceBMethod1() {

	public void interfaceBMethod2() {

In MainClass, we implemented methods defined in interfaceB but still compiler shows the following error message:

The type MainClass must implement the inherited abstract method
The type MainClass must implement the inherited abstract method

InterfaceB extends from InterfaceA, so MainClass which is implementing interface InterfaceB has to implement abstract methods of both interfaces.

Easy way in Eclipse is to right click the class name > Source > Override/Implement Methods

You will see the following:
Impleminting abstract methods
You have to implement all the abstract methods.

Submit "Interface extending Interface" to Facebook Submit "Interface extending Interface" to Digg Submit "Interface extending Interface" to Submit "Interface extending Interface" to StumbleUpon Submit "Interface extending Interface" to Google