Why use interfaces?

What is the point in interfaces?
I understand that you can use them to ensure a class implements certain methods. Why does this need to be done?
Do they have any other use?
thank you
mike

Interfaces are used for a number of reasons. Consider:
1. Java is a strongly-typed language which means that any when a method is called on an Object (non-reflectively), at compile-time that method must be known to exist on the Object.
2. Java does not support multiple-inheritance.
Now, suppose you decide to implement the Event model. Interfaces are a very powerful way of allowing you to do this. Providing an abstract superclass that has an abstract actionPerformed() method would suffice, but be unnecessarily restrictive (lack of multiple inheritance). So why not define an interface as a "type"? The Object which is being listened to can inform its listeners via this method. It is excellent for encapsulation as the listened-to object is unable to invoke anything else on the listener other than actionPerformed() (or whatever) and cannot do anything naughty that you don't want it to.
A fundamental principal of OO is to separate interface and implementation. What better way that to make interface and implementation a fundamental part of the language?
Also consider:
You have a massive application that uses Set-like objects all over the place. In your code, when creating new ones and passing around references you do so by the class HashSet (and explicitly constructing them). Supose on switching-on your App you find that it performs like a dog and identify that it is poor HashSet performance at fault. You decide to buy-in a superfast Set-like object from a vendor. Oh dear, you have to do a global search-and-replace on all of your code. Had you used Factories and interfaces, though you would have...
public class CollectionFactory {
  public static java.util.Set newSet() { return new HashSet(); }
  //etc
//and the implementation...
public void myMethod() {
  Set s = CollectionFactory.newSet();
  //pass the INTERFACE Set around
}You now only have to change ONE line to switch implementations. Super! Note this is the entire point of the J2EE specification. Sun define APIs that handle database-connectivity, server-side processing (Servlets) etc etc. and you and I are free to buy the implementation from whichever vendor we prefer.

Similar Messages

  • Why use Interface?

    My question is : Why we use Interface?There is all most same class & interface.at the 1st time we declare method or variables in the interface.2nd time we also declare them when we implements.So i am not clear why i use interface

    Hello,
    When you write an interface I, you can write methods in other classes with I en parameter without knowing what the object is.
    When you write this method, you are sure that these methods exist in the object.
    An interface is a behaviour.
    You can use many very different objects which have the same behaviour :)
    example:
    public interface Moveable
       void move();
    public class StupidMan
      public void kick(Moveable m)
         m.move();   // The object m can be moved, but that's just you know
    public void mouse implements Moveable
    public void car implements Moveable
    public void table implements Moveable
    public void computer implements Moveable

  • Why to use Interface if methods are not implemented??

    Hello,
    I am having a problem to clearify as, why to use the interfaces which defines only methods and no implementation??
    When a class implements an interface the methods are implemented by the class itself, don't you think that the same functionality can be achieved if the class defined the method itself...
    The why to use interfaces, just that the same method name can be used by many classes or some other reasons..

    did you google on that? There is lots of information I am sure explaining why you code to an interface defined type rather than a class defined type.
    However, fundamentally you are correct, classes define their own type. The idea is that you use an interface because it allows you to have more than one implementation. Plus you can more easily change the structure of your program if you later wish if you did not use the class type directly.
    You get better answers if you ask in the Patterns forum below.

  • Why not use interfaces for constants?

    Hi,
    I have been getting conflicting views about why not use interfaces for constants?
    Can anyone shed some light on it?
    Piyush

    How so?
    If the constants are only used in a single classhow
    does it help to put them in a separate structute?
    (Ignoring the a type safe enumeration of course.)Well, mainly for readability. Suppose that you have a
    web application which has a servlet class
    "RedirectServlet", which takes a variable to redirect
    to a given JSP file. In the JSP files, you want to
    create forms which take this servlet as their action.
    You could of course put all these "redirect"
    constants in the RedirectServlet itself, but then
    it's kind of weird that you have to import a
    servlet in your jsp file to include these constants
    and to be able to write
    <form action="servlet/RedirectServlet?key=<%=
    RedirectServlet.HOMEPAGE %>> or so.
    Instead, you could create an interface called
    "RedirectConstants", and then your servlet
    RedirectServlet could implement this interface. Then
    your JSP can also access these constants via this
    interface.
    But then again, this is merely a matter of style, I
    fully agree that there is never a real _need_ to put
    constants in a separate structure if they're only used
    in a single class.Are you claiming that your example above is a single class?

  • Why use an interface?

    Hey everybody,
    I posted a message in another thread about why to use an abstract class. I have another question and again I am not asking how but why and when. But this time about interfaces. Why would I need to write one? Any example that is not too technical would be great!
    I have read a lot about interfaces but mostly it explains how to write one and not when and why to use them.
    Thanks in advance for your help!

    807479 wrote:
    So my question is basically how does implementing an interface help if there is no code in any of the methods?Because it says to anyone who wants to know "this class fulfills the contract for <tt>x</tt>", where <tt>x</tt> is the behaviour (methods) associated with the interface.
    Furthermore, in the same way that the language allows you to use a superclass as a type, it also allows you to use interfaces as types.
    I presume you're aware that an object can be passed to any method that takes its superclass; well, it can also be passed to any method that takes an interface that it implements.
    <tt>String</tt>, for example, implements <tt>Comparable</tt> (a good real-world interface to get familiar with, BTW), so a <tt>String</tt> object can be passed to either of the following methods:public String append(String s)...
    public int compareWith(Comparable c)...Now, how does that help you? Suppose you write a program that uses a <tt>List</tt>. A common beginner's mistake is to type everything to the nth degree, viz:ArrayList<String> myList = new ArrayList<String>();and then write methods in the same way:public void addSomeStrings(ArrayList<String> list,
       String... items) {.....but, while it will work, it's quite brittle.
    Suppose you decide later on that an <tt>ArrayList</tt> isn't the best way to store your Strings ... what do you do? You have to refactor every bit of code that took an <tt>ArrayList</tt> to now take a new type of List (eg, a <tt>LinkedList</tt>).
    Suppose instead that you wrote your program as follows:List<String> myList = new ArrayList<String>();and then your methods (hopefully ALL of them) as:public void addSomeStrings(List<String> list,
       String... items) {..... Now to change the program to use a <tt>LinkedList</tt>, the ONLY thing you have to change is:List<String> myList = new LinkedList<String>();and your program will work just fine.
    This is what a lot of the posts that talk about "programming to interfaces" are on about. It's a very good technique to get familiar with.
    HIH
    Winston

  • Why we use interfaces ?

    hi all!
    i m confused that what is the advantage of using interfaces for classes if it is for security,data hiding pupose then we can use private modifiers,then y is this think built in java and which r the cases in which we must use interfaces and y?
    plz give me any simple example to understand ur point
    thanx in advance.
    sajjad ahmad

    Hmm... First, I'm sorry about my English... but i will try.
    In C++ we can use multi-inheritance that let the developer "extends" one or more classes.
    eg.
    class Hello extends A,B,C,D
    This case can be happened in C++.
    But If both class A and B have a method call "void sayMyName()"
    How can we refer which method was called when we call "Hello.sayMyName()"
    A.sayMyName() or B.sayMyName()
    So java don't allow this thing happen.
    Java allow developers to extend "only one class"
    but to enable multi-inheritance ability Java allow developer to implement more than one class.
    That is "interface" which was implemented.
    Now lets talk about it's benefits.
    Interface is not for security or data hiding purpose.
    But interface is used for "make a template".
    When I created one class called Hello.
    But I have created another class too.
    Now I want to make sure that my classed have a method "void say()"
    What can I do ?
    1. Make some class that have a method "void say()" and let my classes extend it.
    2. Make an interface and implement it.
    Choise number one is quite good ... but !!!
    If I have to extend some another class that is more important such as "Applet"
    Now I can't extend another class.
    I need only method "void say()". But I don't care what it does.
    So I make an interface that force the implementing class to create a method "void say()"
    and I implement it.
    Question: Why I have to implement this interface ? If I only define a method "void say()"
    The problems is gone ....
    Answer: That may be true if I want them to have a method. But how can I refer to them.
    Lets see this code.
    class A extends Applet {
    void say() {System.out.println("My name is A");}
    ... go on ...
    class B extends Applet {
    void say() {System.out.println("My name is B")}
    ... go on ...
    class GO {
    public void letMeSay(............. o) {
    o.say();
    What can I fill in the argument of method "letMeSay()"?
    Object ? Object doesn't have a method "void say()"
    Applet ? With the same reason.
    Now lets see another code.
    interface Sayable {
    abstract void say();
    class A extends Applet implements Sayable {
    void say() {System.out.println("My name is A");}
    ... go on ...
    class B extends Applet implements Sayable {
    void say() {System.out.println("My name is B")}
    ... go on ...
    public void letMeSay(Sayable o) {
    o.say();
    It's ok right ... I can refer to interface "Sayable" that can "say"
    Next benefit of interface ... "define Constants field"
    We can define constants in an interface and implements it to everywhere we want to use those constants. When we change a value in this interface ... Constants in another place will be changed too .... that is very useful ....(But this may have change in J2SE 1.5 ... see more info)
    "I HOPE THIS REPLY MAY GIVE YOU SOME KNOWLEDGE ... GOOD LUCK WITH PROGRAMMING"

  • Why an Interface is used in a Java Program

    Since we have Classes in Java program
    Then what is the need for An Interface in a Java Program
    Please explain to me
    i'm confused

    These are fair comments as per as interface is concern.... we need interface to declare the methods without implementing the methods. Basically interfaces help implementing classes in a organised way.
    Now We got abstract class also, which has got more or less same features like interfaces. In abstract class also we can declare a method without implementation.
    If we use abstract class and extend that abstract class, we don't have implement all the abstract methods in that particular class,which would extend the abstract class, but if we implement an interface in a class, we have to define all the methods with their body. Now, can anyone tell me , in a generic way, when do we use interface and when do we use abstract class. I don't need the differences between abstract class and interface...that i know...thanks in advance
    take it easy
    RD
    l

  • Why we use Interface?

    hai
    Can i have a explanation for using Interface (apart from overcoming multiple Inheritance)

    **ACK. Got method names mixed up. Though it doesn't really matter, here is the correct mapping from the original reply, to avoid confusion.** :)
    This is wrong. You can't have an instance of an interface as you have declared here by saying Draggable drag. Interfaces cannot be instantiated. I think what you meant to say is this:
    //understand this is blatantly skeletal
    class ConcreteDraggable implements Draggable {
         //these methods must be defined, even if the definition is merely {}
         dragTo(...) {...}
         calcDistance(...) {...}
    }And then in the script that uses ConcreteDraggable:
    ConcreteDraggable dragThis = new ConcreteDraggable();
    dragThis.dragTo(...);
    dragThis.calcDistance(...);

  • Import invoices using interface table

    Dear all ,
    I want to import invoice from legacy system to oracle EBS R12 , and i use interface table to import the invoice.
    The problem is when i run Payable open interface import concurrent program to import the invoices , it didn't import any invoices
    and the report output didn't show any error or any data according to the invoices.
    Report output :
    Report Date: 27-JUN-2010 11:25
    Page: 1
    Payables Open Interface Import Report
    Hold Name:
    Source Name: Manual Invoice Entry Hold Reason:
    Group: GL Date:
    Purge: No
    Summarize Report N
    Report Date: 27-JUN-2010 11:25
    Page: 2
    Payables Open Interface Import Report
    Hold Name:
    Source Name: Manual Invoice Entry Hold Reason:
    Group: GL Date:
    Purge: No
    Summarize Report N
    So i go to the db and open the interface table and the status was null ,
    i dont know why????????

    Hi ,
    100% org_id problem Please check. Same i faced after i update the org_id it is working fine and showing the output with inovice and rejection details also
    Thanks
    Venkat

  • Why use *31L in the following code?

    Why use *31L in the following code?
    * {@inheritDoc}
    public int hashCode()
    return (int) ((long) getAreaCode() * 31L + getLocalNumber());
    public class PhoneNumber
            implements PortableObject
        // ----- constructors ---------------------------------------------------
        * Default constructor (necessary for PortableObject implementation).
        public PhoneNumber()
        * Construct a Phone.
        * @param nAccessCode   the numbers used to access international or
        *                      non-local calls
        * @param nCountryCode  the numbers used to designate a country
        * @param nAreaCode     the numbers used to indicate a geographical region
        * @param lLocalNumber  the local numbers
        public PhoneNumber(short nAccessCode, short nCountryCode,
                short nAreaCode, long lLocalNumber)
            m_nAccessCode  = nAccessCode;
            m_nCountryCode = nCountryCode;
            m_nAreaCode    = nAreaCode;
            m_lLocalNumber = lLocalNumber;
        // ----- accessors ------------------------------------------------------
        * Return the access code.
        * @return the access code
        public short getAccessCode()
            return m_nAccessCode;
        * Set the numbers used to access international or non-local calls.
        * @param nAccessCode  the access code numbers
        public void setAccessCode(short nAccessCode)
            m_nAccessCode = nAccessCode;
        * Return the country code.
        * @return the country code
        public short getCountryCode()
            return m_nCountryCode;
        * Set the country code.
        * @param nCountryCode  the country code
        public void setCountryCode(short nCountryCode)
            m_nCountryCode = nCountryCode;
        * Return the area code.
        * @return the area code
        public short getAreaCode()
            return m_nAreaCode;
        * Set the numbers used indicate a geographic area within a country.
        * @param nAreaCode  the area code
        public void setAreaCode(short nAreaCode)
            m_nAreaCode = nAreaCode;
        * Return the local or subscriber number.
        * @return the local or subscriber number
        public long getLocalNumber()
            return m_lLocalNumber;
        * Set the local or subscriber number.
        * @param lLocalNumbeer  the local or subscriber number
        public void setLocalNumber(long lLocalNumbeer)
            m_lLocalNumber = lLocalNumbeer;
        // ----- PortableObject interface ---------------------------------------
        * {@inheritDoc}
        public void readExternal(PofReader reader)
                throws IOException
            m_nAccessCode  = reader.readShort(ACCESS_CODE);
            m_nCountryCode = reader.readShort(COUNTRY_CODE);
            m_nAreaCode    = reader.readShort(AREA_CODE);
            m_lLocalNumber = reader.readLong(LOCAL_NUMBER);
        * {@inheritDoc}
        public void writeExternal(PofWriter writer)
                throws IOException
            writer.writeShort(ACCESS_CODE, m_nAccessCode);
            writer.writeShort(COUNTRY_CODE, m_nCountryCode);
            writer.writeShort(AREA_CODE, m_nAreaCode);
            writer.writeLong(LOCAL_NUMBER, m_lLocalNumber);
        // ----- Object methods -------------------------------------------------
        * {@inheritDoc}
        public boolean equals(Object oThat)
            if (this == oThat)
                return true;
            if (oThat == null)
                return false;
            PhoneNumber that = (PhoneNumber) oThat;
            return getAccessCode()  == that.getAccessCode()  &&
                   getCountryCode() == that.getCountryCode() &&
                   getAreaCode()    == that.getAreaCode()    &&
                   getLocalNumber() == that.getLocalNumber();
        * {@inheritDoc}
        public int hashCode()
            return (int) ((long) getAreaCode() * 31L + getLocalNumber());
        * {@inheritDoc}
        public String toString()
            return "+" + getAccessCode() + " " + getCountryCode() + " "
                       + getAreaCode()   + " " + getLocalNumber();
    ...

    31 is a nice prime number that is used here to decrease hash collisions
    thanks,
    -Rob

  • Why use key-partitioning and key-associator features?

    Why use key-partitioning and key-associator features?
    What kind of applications are suitable for using key-associator and key-partitioning features?
    Could you give me some example?
    Thank you

    So the typical way is to use KeyAssociation. This is a single interface that uses a method
    public Object getAssociatedKey();
    I believe this works on the ClusterService level (rather than say the Cache). So, say you have a Client and an Account cache where a Client can have multiple Accounts. Now both the Client and the Account object will implement KeyAssociation and return the client object as the AssociatedKey. This will cause these associated objects to live on the same partition.
    Now you can do some clever tricks since you know these are on the same partition. These include using the BackingMap and EntryProcessors / InvocationService / Aggregators to return all the AccountIds associated with a client account (essentially a join).
    Unfortunately, these are pretty advanced Coherence features so it is worth building them in a testcase first and getting them to work before you integrate them into your application.
    Best, Andrew.
    PS. You could also use the KeyPartitioningStrategy, but I prefer the KeyAssociation (as do most people).

  • What is the advantages of using Interface?

    Hi,
    I still don't get what's the advantages of using interface. Reusability? is it the main advantage? thanks in advance.

    What is GOF?
    Interface is a good program practice when working with RMI (Remote Method Invocation) application. Imagine your anti-virus. When you connect to internet your software invoke a method into your software vendor site and download the new definitions. Now every anti-virus Subscription is different. The method you invoke, will depends on your Subscription. If you hard code the method abstractly, you will not achieve this functionality.
    Another concept is that because Java does not practice multile inheritance interface is a goog way to interface into another class.
    Example
    I want to extends to multiple class which java do not support. I will write an interface i.e I want to extends to FileOutputStream, OutputStream, Object, Integer, String, ActionEvent, Window etc.
    I will write an interface like this
    interface MyClass {
    pulic void setFileOutputStream ( FileOutputStream file );
    public void setOutputStream ( OutputStream );
    public Object getObject ( );
    public Seriable getInterget ( )
    ------------------- //You get the gist
    With this interface you can implement they behaviours
    You could say, why don't we just import them. When yo import them you have already hard coded there behaviour. But this way you can apply diferent behaviour throughout you application development. And any class that implement them must provide ways of using it.

  • Loading dimensions using interface table

    Hello,
    I am trying to load dimensions into EPMA 11.1.1.3 using interface tables and need some direction. I have an accounts dimension file with the following columns ( Parent, Child, Alias, Description, DataType,Aggregation). I configured a data source using configuration wizard (Interface tables).
    I see in the database that some sample tables are created. Now, should I create a separate table with the columns listed above?
    Can someone let me know what are the next steps to successfully import accounts dimension?
    Thanks

    Can someone plz respond?
    This is important for me. I have gone thru' the documentation and also the sample tables but don't understand why are there multiple tables for a particular dimension viz. hierarchy, property etc?
    Please tell me the right way.
    Thanks again!!

  • Why defining Interface for singleton with getInstance() doesnt work?

    Lets say I want to do the following:
    package adapters
        public interface IAdapter
            function init():void         
            function getInstance():IAdapter
    package adapters
        public class DAAdapter extends EventDispatcher implements IAdapter
            private static var _instance:DAAdapter;
            public static function getInstance():IAdapter {
                if(!_instance)
                    _instance = new DAAdapter();
                return _instance;
            function DAAdapter(target:IEventDispatcher=null)
                super(target);
         public function init() {}
    I getting:
    1044: Interface method getInstance in namespace adapters:IAdapter not implemented by class adapters:DAAdapter.
    Why?

    In AS3 you cannot use interface definitions for static methods.
    http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/statements.html#static

  • Using Interfaces.

    Ok Guys,
    I am a newbie so apologies, and i know you are all going OH no not interfaces.
    I understand interfaces, why to use them when.
    I don't understand them in a program that i am using.
    I have inherited a program that is using interfaces.
    Here is a bit of code:
    public class Playing {
         public static void main(String[] args) {
              Object1 obj = null ;
              Document1 doc = null ;
              Group group = null ;
    We then manipulate these objects.
    NOw when I look in the documentation these are all interfaces.
    Why then in the class do we not use the implements.
    Is this because every class in the package inherits these interfaces so i can just use them as they are? This is the only reason i can think of. So when can we use interfaces as above and when do we use the implements key word.When would i use the new key word or would that just be for a method?
    Thanks.

    You mean that Object1, etcetera are interfaces? Surprise, surprise, I haven't actually thought of interface variables before. But if they exist it must mean that you can assign object references to them of any class that implements the interface. I tried this example,
        public interface I {
            public void m();
        public class C1 implements I {
            public void m() {
        public class C2 implements I {
            public void m() {
            public void mm() {
        void test() {
            I inter;          // interface variable
            inter = new C1(); // okay because C1 implements I
            inter = new C2(); // okay too
            inter.m();     // okay because m part of interface I
    //        inter.mm();  // error because mm not part of interface I
        }The interface variable inter can hold objects of classes C1 and C2 because they implement I, but only methods of interface I can be accessed.

Maybe you are looking for