Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Interfaces. 1 Comment on Java Interfaces

In this article we will look at Java interfaces which are one of the powerful programming constructs which allows programmer to implement abstraction in Java programs. The advantage of an interface is, since interfaces are outside of Java class hierarchy, classes from different hierarchies can implement a common interface.

 

Interface Definition

 

An interface is a collection of method prototypes (method name followed by parameters list without any body). The syntax of a method prototype is as follows:

 

return-type  method-name(parameters-list);

 

An interface can contain only constants and method prototypes. The use of an interface is to abstract the class’ behavior from its definition. In this way an interface can specify a set of method prototypes which can be implemented by one or more classes.

 

Differences between interface and a class

  • Objects can be created for classes, where as it is not possible for interfaces.
  • Classes can contain methods with body, where as it is not possible in interfaces.
  • Classes can contain variables, where as it is not possible in interfaces.
  • Some classes can be final, where as interfaces cannot be declared as final.
  • Some classes can be abstract, where as interfaces cannot be declared as abstract.
  • Various access specifiers like public or private or default can be applied to classes, where as only public or default access specifier is applicable for top-level interface.

 

Defining an Interface

 

The definition of an interface is very much similar to the definition of a class. The syntax for defining an interface is as follows:

 

interface  interface-name

{

return-type  method1(parameters-list);

return-type  method2(parameters-list);

data-type  variable-name1 = value;

data-type  variable-name2 = value;

}

 

Access specifier before interface keyword can be public or default (no specifier). All the methods inside an interface definition does not contain any body. They end with a semi-colon after the parameters list.

 

All variables declared inside an interface are by default final and static. All methods declared inside an interface are by default abstract and both variables as well as methods are implicitly public.

 

An example for Java interface is as follows:

 

public interface IMovable 
{
	void crawl();
	void run();
	void jump();
}

 

In the above example, IMovable is the interface name which contains three methods crawlrun and jump.

 

Implementing Interfaces

 

The methods declared in an interface definition must be implemented by the class which inherits that interface. This process of a class implementing the methods in an interface is known as implementing interfaces.

 

It is mandatory for a class to implement (provide body) all the methods available in an interface. Otherwise, if a class provides implementation for only some methods (partial implementation) then the class should be made abstract.

 

The methods of the interface must be declared as public in the class. Syntax for implementing an interface is as follows:

 

class ClassName implements InterfaceName

{

//Implementations of methods in the interface

}

 

Let’s consider two classes Animal and Person which implements the interface IMovable defined above:

 

abstract class Animal implements IMovable
{
	abstract void area();
}

class Person implements IMovable
{
	@Override
	public void crawl()
	{	
		System.out.println("Person is crawling.");
	}
	@Override
	public void run() 
	{
		System.out.println("Person is running.");
	}
	@Override
	public void jump() 
	{
		System.out.println("Person is jumping.");
	}	
}

public class Driver 
{
	public static void main(String[] args) 
	{
		Person ramesh = new Person();
		IMovable obj = ramesh;
		obj.crawl();
		obj.run();
		obj.jump();
	}
}

 

In the above example, Person class provides implementation for methods in the interface IMovable.

 

Nested Interfaces

 

An interface which is declared inside a class or another interface is called a nested interface or a member interface. A nested interface can be declared as public, private or protected. Let’s look at an example of how to create and use a nested interface:

 

class A
{
	int x;
	public interface IA
	{
		void method();
	}
}

class B implements A.IA
{
	public void method()
	{
		System.out.println("Method implemented successfully");
	}
}

public class Driver 
{
	public static void main(String[] args) 
	{
		A.IA obj = new B();
		obj.method();
	}
}

 

In the above example nested interface is IA. A fully qualified reference must be used (as in A.IA) to reference a nested interface outside the enclosing class or interface. The output of the above program is Method implemented successfully.

 

Applying Interfaces

 

The real power of interfaces lies in separating the specification of methods from their implementation in a class. Interfaces enables developers of classes to implement the methods using different algorithms of their choice.

 

A user can use any of the available implementations by simply creating an object of that class. An example demonstrating this use of interfaces is as shown below:

 

ISwap.java (Interface)

public interface ISwap 
{
	void swap(int x, int y);
}

 

SwapTemp.java (Uses a temporary variable to swap the two values)

public class SwapTemp implements ISwap
{
	public void swap(int x, int y)
	{
		int temp;
		temp = x;
		x = y;
		y = temp;
		System.out.println("After interchange, x = " + x + ", y = " + y);
	}
}

 

SwapNoTemp.java (Doesn’t use any third variable to swap the two values)

public class SwapNoTemp implements ISwap
{
	public void swap(int x, int y)
	{
		x = x + y;
		y = x - y;
		x = x - y;
		System.out.println("After interchange, x = " + x + ", y = " + y);
	}
}

 

Driver.java (Main program)

public class Driver 
{
	public static void main(String[] args) 
	{
		ISwap s = new SwapTemp();
		s.swap(10, 20);
		s = new SwapNoTemp();
		s.swap(10, 20);
	}
}

 

The output of the above program is:

 

After interchange, x = 20, y = 10
After interchange, x = 20, y = 10

 

Note that there is no change in the output in the two calls. So, while making the above code public for users, only source file for the interface and the .class files of the two classes will be provided.

 

Variables in Java Interfaces

 

An interface can contain constants (final variables). A class that implements an interface containing constants can use them as if they were declared in the class. Example demonstrating constants in an interface is given below:

 

IArea.java (interface)

public interface IArea 
{
	double PI = 3.142;
}

 

Driver.java (Main program which implements the above interface)

public class Driver implements IArea
{
	public static void main(String[] args) 
	{
		System.out.println("PI value is: " + PI);
	}
}

 

In the above code the class Driver.java implements the interface IArea and prints the value of the constant PI. Output of the above program is: PI value is: 3.142.

 

Extending Interfaces

 

Like classes, interfaces can also be extended to provide new functionality. Like classes, we use extends keyword for extending an interface. Syntax for extending an interface is given below:

 

interface NewInterface extends OldInterface

{

//Method prototypes here

}

 

Some people might think instead of creating a new interface and extending the existing interface, why can’t we include the new functionality in the existing interface directly? We can’t because the applications of people who are using the existing interface will break if new functionality is included. To avoid that we create a new interface.

 

All classes which implement the new interface must provide implementation for all the methods in the new interface plus for methods in its parent interface. Following example demonstrates extending an interface:

 

IArea.java (Parent interface)

public interface IArea 
{
	double PI = 3.142;
	void area();
}

 

IAreaPeri.java (Child interface)

public interface IAreaPeri extends IArea
{
	void peri();
}

 

Driver.java (Main program)

class Shape implements IAreaPeri
{
	public void area()
	{
		System.out.println("Area of shape");
	}
	public void peri()
	{
		System.out.println("Perimeter of shape");
	}
}

public class Driver
{
	public static void main(String[] args) 
	{
		Shape s = new Shape();
		s.area();
		s.peri();
	}
}

 

In the above example, class Shape implements the interface IAreaPeri and provides implementation for both methods area() and peri(). Output of the above program is:

 

Area of shape
Perimeter of shape

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

1 Comment

You can follow any responses to this entry through the RSS 2.0 feed.

In java 8 we can define static and default methods in an interface

Leave a Reply

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