Home > Tutorial > Java Interface Explained

Java Interface Explained

So what is a Java interface? It’s actually a really good question because I have found many Java programmers that have never used an interface in their Java programming activities. I suspect this is the case because maybe they don’t understand the concept and benefit of an interface.

A Java interface is similar to a Java class. However, a Java interface can only contain method signatures and data fields. A Java interface can define methods, including the input and output, but not contain the actual implementation code within the method. Let’s take a look at the sample Java Interface below.


Define Java Interface

We have defined a simple interface that contains a variable called “greeting”. It also contains two methods: jcdGreeting() and jcdRoundIt().

package com.jcd.java.tutorials;

public interface JavaCodeDepotInterface 
{
	public String greeting = "Java Code Depot Inteface Says Hello";
	
	public void jcdGreeting();
	
	public void jcdRoundIt(int number);
}


All of the methods in an interface are public and abstract. In order for you to implement an interface, the implementing class do the following:

  • It must use the Java implements clause for class declaration.
  • It must implement every method declared within the interface.


Implement Java Interface

As you see below, the variable “greeting” can be accessed directly from the interface. When implementing the methods, the class must use the same format as what is defined in the interface for each method.

package com.jcd.java.tutorials;

public class JavaCodeDepotInterfaceImpl implements JavaCodeDepotInterface
{

	public void jcdGreeting()
	{
		System.out.println(JavaCodeDepotInterface.greeting);
	}
	
	int number = 999;
	
	public void jcdRoundIt(int number)
	{
		System.out.println(Math.round(number));
	}

}


Why Use Java Interfaces?

Implementing an interface in Java allows the class to be more formal about the behavior of the methods within the interface. Think of this as a contract between the class and the world. This contract is enforced at build time by the compiler. If your implementing an interface, all methods defined by the interface must appear in the source code before the class will successfully compile.


Seymour
Posted by

Seymour

I have been a software developer for twenty years now focusing on writing high quality Java applications. If you are in a programming field, you know that technology is constantly changing. You have to keep current or you will get left behind!

You may also like...

Leave a Reply

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

Copyright © 2018 JavaCodeDepot