• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

Basics of Java Interface Usage

October 9, 2013 //  by Manisha Patil//  Leave a Comment

In this article we will see how to use Java interfaces correctly with with some examples. Using Java as Interfaces is often not used or wrongly used. This article demonstrates the practical uses of Interfaces in Java. First of all it is important to understand what is an interface?
Let us create a “contract” where the class that implements shall obey it. In Listing 1 we will see how to create a simple interface in Java.

Listing 1 : My first interface

package net.javabeat;

public interface MyFirstInterface {
	/** Methods that must
	 * Must be implemented by
	 * Class that implements this interface */
	public void method1();
	public int method2();
	public String metodo3(String parameter1);
}

Note, in this interface methods have no body, and only have signature. Now we have a “contract” that must be followed if someone implements this interface. See in Listing 2, a class that implements our above interface.

Listing 2 : Implementing the Interface

package net.javabeat;

public class MyClass implements MyFirstInterface {
	@Override
	public void method1() {
		// TODO Auto-generated method stub
	}

	public int method2() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String metodo3(String parameter1) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * @ Param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

When using the keyword “implements” in MyClass, you will see that the IDE (Eclipse, Netbeans, etc.) warns you to implement the methods declared in the interface.

Practical Uses of Interface

Having basic knowledge of an interface, let us now understand its use in real time.

The interface is widely used in large projects to force the programmer to follow the pattern of the project, this is a contract where a coder is obliged to implement its methods, and the class must always follow the standard implementation of the interface. Assume the following case: Let’s say that an Interface BasicDAO of our project contains declaration of methods that any DAO class should have. Say any DAO class will have CRUD methods.

  • What is Hibernate ORM Framework?

Listing 3 : Our DAO Interface

package net.javabeat;

import java.util.List;

public interface BasicoDAO {
	public void save (Object bean);
	public void update (Object bean);
	public void delete (int id);
	public Object GetById (int id);
	public List<Object>  getAll ();
}

Now let’s say, one of the developers who is working in HR module wants to create a DAO to perform CRUD operations on employee object. Now he will implement the above interface.

Listing 4 : Implemented Interface DAO

package net.javabeat;

import java.util.List;

public class EmployeeDAO implements BasicoDAO {
	@Override
	public void save(Object bean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void update(Object bean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void delete(int id) {
		// TODO Auto-generated method stub

	}

	@Override
	public Object GetById(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Object> getAll() {
		// TODO Auto-generated method stub
		return null;
	}

	// Method part created and defined by the programmer
	public void SalaryCalculation() {

	}

}

We now have all the items, let’s now use it in our application. Suppose a new programmer (has not created the class EmployeeDAO), and wants to insert a new employee. Say this new programmer has no idea how the interface was implemented by EmployeeDAO, he doesn’t even have access to this class, but he knows something much more important. He will use the power of polymorphism and create a new object EmployeeDAO of type BasicoDAO. See Listing 5.

Listing 5 : Using polymorphism

package net.javabeat;

public class MyApp {
	/**
	 * @ Param args
	 */
	public static void main (String [] args) {
		BasicoDAO  emplyoeeDAO = new EmployeeDAO();

		emplyoeeDAO.save(employee001);

	}
}

Note that we create the object EmployeeDAO of type BasicoDAO , so we can only call the methods of the interface BasicoDAO. But most  important is that the new programmer who uses the class EmployeeDAO, can call the methods described in the interface. What forces the programmer who created the class EmployeeDAO implements BasicoDAO? 

Few Java Basic Tutorials:

  • Java Generics
  • Java Annotations

You can create EmployeeDAO without implementing the interface, but the new scheduler that uses this class will not achieve polymorphism and you will see that the class is wrong as per standards. There is another way of knowing if the class that the interface was created by BasicDAO, see in Listing 6.

Listing 6 : Using the instanceof

package net.javabeat;

public class MyApp {
	/** * @param args */
	public static void main(String[] args) {
		EmployeeDAO employeeDAO = new EmployeeDAO();
		if (employeeDAO instanceof BasicoDAO)
			employeeDAO.save(employee001);
		else System.err.println("The class EmployeeDAO does not implement BasicoDAO ,
                         no procedure was performed");
		}

}

Marker Interface

There is also a concept that we call: Marker Interface.These interfaces serve only to make classes, so that when performing “instanceof” we can test a class .

Let’s try another example: We have an Employee interface without any methods or attribute, because it is just a marker interface. See in Listing 7.

Listing 7 : Interface Markup Employee

public interface Employee {

}

Now let us create 3 Beans, which correspond to three distinct types of employees: Manager, Coordinator and Operator all implementing Employee.

Listing 8 : Creating Manager, Coordinator and Operator

package net.javabeat;

public class Manager implements Employee{
	private int id;
	private String name;
}

package net.javabeat;

public class Coordinator implements Employee{
	private int id;
	private String name;
}

package net.javabeat;

public class Operator implements Employee{
	private int id;
	private String name;
}

Now in our application we have a method that performs a procedure for calculation of salary for each different type of employee. Now lets say we don’t use the interface and make the implementation as below.

Listing 9 : Misuse Interface Markup

package net.javabeat;

public class MyApp {
	/** * @param args */

	public void toCalculateManagerSalary(Manager manager) {

	}

	public void toCalculateCoordinatorSalary(Coordinator Coordinator) {

	}

	public void toCalculateOperatorSalary(Operator operator) {

	}

}

Much work can be reduced to only 1 method, as shown in Listing 10.

List 10 : Using the marker interface

package net.javabeat;

public class MyApp {

	public void calculaEmployeeSalary(Employee employee) {

		if (employee instanceof Manager) {
			// Calculate for manager Salary
		} else if (employee instanceof Coordinator) {
			// Calculate for coordinator salary
		} else if (employee instanceof Operator) {
			// Calculate for operator salary
		}
	}
}

Rather than creating a method for each type of employee, everything together in just 1 using the marker interface.

Summary

When properly used, an interface eventually becomes a powerful tool in the hands of a programmer or analyst, and it is essential to use in day-to-day programming. Good programming practices governing the use of an interface is essential for a good software design.

Category: JavaTag: Java

About Manisha Patil

Manisha S Patil, currently residing at Pune India. She is currently working as freelance writer for websites. She had earlier worked at Caritor Bangalore, TCS Bangalore and Sungard Pune. She has 5 years of experience in Java/J2EE technologies.

Previous Post: « Working With dojo/dom-construct – DOM construction API in DOJO
Next Post: Use dojo/keys For Key Press Events in DOJO »

Reader Interactions

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact