View RSS Feed

My Java Tips

Working With Interfaces

Rate this Entry
by , 11-08-2011 at 06:33 PM (491 Views)
Interface is very much similar to the Abstract class in Java but the difference is that in interfaces, members (methods) cannot be implemented, member(fields) defined will be treated as constants.
A class becomes more formal about its behavior after implementing an interface. Interfaces are actually a contract between the class and the outside world. While implementing an interface in a concrete class, you have to implement all the methods defined by that interface. If you miss any method, compilier will show errors.




Java Code:
public interface MyInterface {
	public int calSum(int a, int b);

	public String changeToUpperCase(String a);

	public boolean checkAmount(int a);
}

public class ImplatationClass implements MyInterface {

	// implementation of calSum method
	public int calSum(int int_a, int int_b) {
		return int_a+int_b;
	}

	// implementation of changeToUpperCase method
	public String changeToUpperCase(String str_a) {

		return str_a.toUpperCase();
	}

	// implementation of checkAmount method
	public boolean checkAmount(int int_a) {
		if(int_a>100)
			return true;
		else
			return false;
	}

}

public class MainClass {

	public static void main(String []str){

		ImplatationClass obj = new ImplatationClass();
		System.out.println("Sum of 10 and 20 is: " + obj.calSum(10, 20));
		System.out.println("apple is upper case:  " + obj.changeToUpperCase("apple"));
		System.out.println("115 is greater than 100: " + obj.checkAmount(115));

	}

}
Output:
Sum of 10 and 20 is: 30
apple is upper case: APPLE
115 is greater than 100: true

You are supposed to implement all the methods in ImplementationClass which you defined in your interface. If you miss any, compilier will throw errors. For example:
Java Code:
	// MyInterface is same as declared above
public class ImplatationClass implements MyInterface {

	// implementation of calSum method
	public int calSum(int int_a, int int_b) {
		return int_a+int_b;
	}

	// implementation of changeToUpperCase method
	public String changeToUpperCase(String str_a) {

		return str_a.toUpperCase();
	}	

}
Compiler throws this error message:
The type a must implement the inherited abstract method MyInterface.checkAmount(int)

Submit "Working With Interfaces" to Facebook Submit "Working With Interfaces" to Digg Submit "Working With Interfaces" to del.icio.us Submit "Working With Interfaces" to StumbleUpon Submit "Working With Interfaces" to Google

Categories
Java SE

Comments