Working With Interfaces

10 April 2007

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.

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:
 
	// 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)

del.icio.us:Working With Interfaces  digg:Working With Interfaces  spurl:Working With Interfaces  wists:Working With Interfaces  simpy:Working With Interfaces  newsvine:Working With Interfaces  blinklist:Working With Interfaces  furl:Working With Interfaces  reddit:Working With Interfaces  fark:Working With Interfaces  blogmarks:Working With Interfaces  Y!:Working With Interfaces  smarking:Working With Interfaces  magnolia:Working With Interfaces  segnalo:Working With Interfaces  gifttagging:Working With Interfaces

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Working With Interfaces

Leave a Reply