Understanding interface
Interface is a contract among the collaborating objects. Basically object specify set of methods by which objects expose "set of functionality" and operation. If set of operation is common among the collaborating objects then we can said that those method provides standard means of collaboration.
Interface is a surface for the collaborating objects, with set of rules that must followed by the implementing classes.
Defining interface:
The interface IDisplay declares the general rules that must be implement by the implementing classes.
Code Snippet 1:
package com.simplify.java.coding;
/**
* @author Ashish.Chudasama
*/
public interface IDisplay {
/*
* Status of readContent method
*/
int READ_SUCCESS = 1;
int READ_FAIL = -1;
/*
* validation status
*/
int VALID_DATA = 2;
int INVALID_DATA = -2;
// read content from the specific path
int readContent(String path);
//validate the content
int validate();
// format the content if required
void formatContent();
//display the content
void renderContent();
}
Key Points:
1) Method declares within an interface are always “public abstract”, means if an interface declares “ void renderContent(); “ is equivalent to “public abstract void renderContent();”.
2) Interface enforces the set of rule(s) by declaring method(s) as abstract but at the same time it does not deal with the implementation. This is based on philosophy “what I am expected but how you achieve is not my concern “. This Philosophy shows the power of runtime polymorphism in object oriented paradigm.
3) Interface method cannot be final. The interface methods are a like empty contract and empty contract can’t be final contract. Hence methods of interface can’t be declared final.
4) Only “public” and “abstract” are two legal modifiers. Private and protected are not allowed because interface leverage the openness and that cannot be restricted.
5) Interface used to connect discontinuous hierarchy structure (in terms of inheritance).
6) By default variables declared within interface are “public static final”, means declaring int READ_SUCCESS = 1; is equivalent to public static final int READ_SUCCESS = 1;
7) Inner class can be declared within an Interface.
Inner class within interface
Code Snippet 2:
This code snippet shows the declaration of inner class within the interface. This interface also implements the NULLObject design pattern to demonstrate the inner class used within the interface.
Yes, this is not the right ways to used NULLObject design pattern but the time begin to illustrate the how to declare and used the inner class within the interface I have prefer this example.
IAlert is a common interface declares to streamline the interactions with the user and provide the appropriate notification as and when required.
Example if we have to display alerts in swing. we create a class that implements the IAlert and provide custom JOptionAlerts ,similarly need to redirect alerts to the console, then create JConsoleAlert class and dispatch the alerts using appropriate factory method.
package com.simplify.java.coding;
/**
* @author Ashish
*This is generic interface to show alert to the user.
*/
public interface IAlert {
IAlert NullAlert =new NullAlertObject();
public boolean show(String msg);
/*
* This Inner class implements the nullObject design patter to
* avoid null check.
*/
class NullAlertObject implements IAlert
{
//show message display successfully
@Override
public boolean show(String msg) {
return true;
}
}
}
Key points:
1) By default inner class declared within the interface are static class, means static class NullAlertObject implements IAlert is equivalent to class NullAlertObject implements IAlert.
2) We can extend the static class declared within the interface with the help of extends keyword. Class accessibility is depends on the visibility of the interface.
3) Interface doesn’t allow declaring inner class as private because only public and default access specifiers are allowed.
4) Inner class can be marked as final to prevent further inheritance.
5) Declaring interface within inner class is valid.
Code Snippet 3:
Extend the inner class declared within IAlert interface.
package org.simplify.java.coding;
import com.simplify.java.coding.IAlert;
/**
* @author Ashish.Chudasama
*/
public class ExtendIAlert extends IAlert.NullAlertObject
{
/** additional functionality if required */
}
Code Snippet 4:
Declaring inner class as a singleton class within interface
package com.simplify.java.coding;
/**
* @author Ashish.Chudasama
* This example shows the inner class as a singleton object
*/
public interface IAlert
{
IAlert NullAlert = NullAlertObject.getInstance();
public boolean show(String msg);
/* This Inner class implements the nullObject design patter to avoid null check.
*/
static class NullAlertObject implements IAlert
{
private static NullAlertObject singleton=new NullAlertObject();
//private constructor to avoid direct instantiation of NullAlertObject class.
private NullAlertObject(){}
//sttaic method to access the singleton object
public static NullAlertObject getInstance()
{
return singleton;
}
// show message display successfully
@Override
public boolean show(String msg)
{
return true;
}
}
}
As per the NullObject design pattern Nullobject is not required to create again and again by declaring NullObject as a singleton object.
Declaring interface within a class
Code Snippet 5:
package com.simplify.java.coding;
public class EmbeddedInterface
{
interface IFeedback
{
void execute();
}
}
Embeddedinterface class declares the IFeedback as inner interface within the class.
Code Snippet 6:
Cyclic dependency not allowed means class declaring inner interface can’t implements itself.
package com.simplify.java.coding;
public class EmbeddedInterface implements EmbeddedInterface.IFeedback
{
interface IFeedback
{
void execute();
}
}
Note: Code snippet 6 unable to compile due to cyclic dependency.
Code snippet 7:
This code demonstrate how to extend the interface declare within a class.
package org.simplify.java.coding;
import com.simplify.java.coding.EmbeddedInterface;
/**
* @author Ashish.Chudasama
*/
public class MyFeedback implements EmbeddedInterface.IFeedback
{
@Override
public void execute()
{
// TODO Auto-generated method stub
}
}
Key points:
1) By default interface declare within a class are static means static interface IFeedback is equivalent to interface IFeedback in code snippet 6.
2) Scope and visibility of interface declared within a class depends on visibility of the outer class.
gr8 article, important points in this article that i found are,
ReplyDelete1) Null Object design pattern.
2) class's inner Interface.
3) class's inner interface implementation.
Now, I am eager to know about it's real life usage.
Thanks.
-----------------------------------------------
ReplyDelete----Consolidated Comments from the Linkedin----
http://www.linkedin.com/groupItem?view=&gid=145246&type=member&item=49986637&qid=40aa38d0-c026-4b3c-99e2-df7b47b213df&goback=.gmp_145246
-----------------------------------------------
Stefano Fago •
Hi,
you blog is clear and effective, good job.
What about your post here?!?!
About Java Interface... it's all right but i think we must see what happen nowday. Interfaces are contracts and this is the main purpose. The Inner possibilities are a way to express a scope such like it does a package; in a design point a view an "inner" of an interface is a thing that it's "owned" by a context.
In new Java, from jkd5 and up, the presence of annotation have changed the way to use Interfaces: marker interface, inner elements in interface are design valid but no more used.
So nowday, an Interface remains a Type used for specify a Role and simulate multiple inheritance (there's also inheritance evolution due to Generics) or a technical tools to do in the right way dynamic proxies in the scope of AOP.
What do you thing about this situation? Do You want to explore these different aspect and propose and new post, to make all designer partecipate?
Thanks for You Time.
Good Job
Stefano
------------------------------------------------
Ashish Chudasama • Hi Stefano,
Thanks for your valuable comment.
Yes, Annotation brings the new dimension to the programming paradigm and simplifies the coding. Annotation is an interface, which is further annotated with the policy to express the applicability and scope. Now a day majority of framework heavily design using annotation to simplify the coding.
Yes Stefano, We can post the new thread in linkedin to address the future aspect of the coding meanwhile I will try to address such concept on my blog too.,
Thanks
Ashish
------------------------------------------------
Mani Swaminathan • By principles of Design Patterns "Code to an Interface and not to an Implementation" but traditional programming (no offense) and working systems have been implemented using procedural systems and more so of Object oriented design, this leads us to have implementations that are not going to be totally decoupled, but coupled most of the times. that being said, Interface does not provide Intellectual Property protection, and provides flexibility. Well it is what you are developing Vs What you are developing for. I like Interfaces to provide a framework, more so of Design Patterns and some abstraction/implementation for IP protection.. and it depends based on implementation
Hi Ashish,
ReplyDeleteThis is a nice article you have provided. It really clears the concepts. But I just want to correct for the sentence
"Basically object specify set of methods by which objects expose "set of functionality" and operation."
should be
"Basically object specify set of methods & variables by which objects expose "set of functionality" and operations."
Object will be always with variable (as a good practise but not necessary) even though you put a single operation or multiple operations....
also it will be nice to look
sample application for
-clustering
-load balancing
-Running PHP with Web Server (generic code)
etc...
Nice article Ashish !!!! Keep posting...:)
Nice one Ashish
ReplyDelete