View RSS Feed

My Java Tips

Implementing more than one Interfaces

Rate this Entry
by , 11-13-2011 at 11:37 AM (2895 Views)
Interfaces contain abstract methods that implementing class has to implement. It is must for the implementing class to implement all the methods found in the interface. Sometimes you face a situation where you have to implement more than one interface. How to do that?


One way is to simply try to write one interface with all the abstract methods. This is not at all flexible as all of these interfaces might be used in different scenarios. So its better to keep each as a separate interface.

Another option is that interface extend each other. This is also not flexible. Review the example below:

Java Code:
public interface InterfaceA {
	public void interfaceAMethod1();
	public void interfaceAMethod2();
}

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

public interface InterfaceC extends InterfaceB {
	public void interfaceCMethod1();
	public void interfaceCMethod2();
}

public class MainClass implements InterfaceC {

	public void interfaceAMethod1() {
		// TODO Auto-generated method stub

	}

	public void interfaceAMethod2() {
		// TODO Auto-generated method stub

	}

	public void interfaceBMethod1() {
		// TODO Auto-generated method stub

	}

	public void interfaceBMethod2() {
		// TODO Auto-generated method stub

	}

	public void interfaceCMethod1() {
		// TODO Auto-generated method stub

	}

	public void interfaceCMethod2() {
		// TODO Auto-generated method stub

	}
}
The right way is to implement all the interfaces in the required class and then provided the implementation of all the abstract methods. In Java, you cannot extend more than once class but you can implement more than one class. Review the example below:

Java Code:
public interface InterfaceA {
	public void interfaceAMethod1();
	public void interfaceAMethod2();
}

public interface InterfaceB{
	public void interfaceBMethod1();
	public void interfaceBMethod2();
}

public interface InterfaceC {
	public void interfaceCMethod1();
	public void interfaceCMethod2();
}

public class MainClass implements InterfaceA,InterfaceB,InterfaceC {

	public void interfaceAMethod1() {
		// TODO Auto-generated method stub

	}

	public void interfaceAMethod2() {
		// TODO Auto-generated method stub

	}

	public void interfaceBMethod1() {
		// TODO Auto-generated method stub

	}

	public void interfaceBMethod2() {
		// TODO Auto-generated method stub

	}

	public void interfaceCMethod1() {
		// TODO Auto-generated method stub

	}

	public void interfaceCMethod2() {
		// TODO Auto-generated method stub

	}
}

Submit "Implementing more than one Interfaces" to Facebook Submit "Implementing more than one Interfaces" to Digg Submit "Implementing more than one Interfaces" to del.icio.us Submit "Implementing more than one Interfaces" to StumbleUpon Submit "Implementing more than one Interfaces" to Google

Comments