How to write interfaces in java or Android?

By | February 7, 2013

This tutorial is about how to use interfaces in java or Android.

What is an Interface?

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.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways:

  • An interface can contain any number of methods.

  • An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.

  • The bytecode of an interface appears in a .class file.

  • Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

  • You cannot instantiate an interface.

  • An interface does not contain any constructors.

  • All of the methods in an interface are abstract.

  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

  • An interface is not extended by a class; it is implemented by a class.

  • An interface can extend multiple interfaces.

Sample Code

Here I will show you how to do it in Android or Java.
This example is for Android.

So can we start.

This is the interface that I am going to implement.

package com.coderzheaven.interfacetest1;

public interface MyTestInterface {

	void testFunctionOne();

	void testFunctionTwo();


Now we will write the activity that implements the above interface.

package com.coderzheaven.interfacetest1;

import android.os.Bundle;

public class MainActivity extends Activity implements MyTestInterface {

	protected void onCreate(Bundle savedInstanceState) {

	public void testFunctionOne() {
		System.out.println("Print from testFunctionOne in the Interface");

	public void testFunctionTwo() {
		System.out.println("Print from testFunctionTwo in the Interface");

Ok Done. Go on and Run it.

Website Pin Facebook Twitter Myspace Friendfeed Technorati Digg Google StumbleUpon Premium Responsive

Leave a Reply

Your email address will not be published. Required fields are marked *