Why interfaces?

I have difficulties in understanding why would I use an interface if I wanted to communicate between two (or more) classes.
Because the interface is by definition abstract, every class implementing the interface has to accept all of its methods (if not declaring itself abstract as well). I only mention this because I understand it, to get to what I don't:
Why would I want to communicate between classes with an interface, if I can do it without? Each class only shares the name of a method in an interface, nothing more. (Is this so?)
If I wanted to execute a series of commands (a method) from another class by calling a method implemented from an interface, how could I do this through an interface? It seems I cannot, while I thought this was the reason to implement interfaces in the first place.
Please clear my scrambled thoughts.

Hi bec!
I have exactly the same problem understanding the
interface concept. I still don't get it from
DanPerkins' code example; if you remove the interface
definition, and the implements bit out of each of the
classes, the code still works. So what's the added
value of the interface. Also, code to turn the tv on
is not the same as to turn on the stereo, so there
isn't any code reuse either. Confused.You use interfaces to keep your classes from having intimate knowledge of each other. Say you're writing code to operate a register/scanner at a grocery store. Everytime your store gets a new kind of item in inventory, you don't want to have to update your class to handle the new item.
class Register {
  double scan( Banana b ) {
    return b.getPrice();
  double scan( Rice r ) {
    return r.getPrice();
  // etc., etc.
}This approach means that Register is tied at the hip to every food item class in the store. Isn't it much nicer to write Register this way:
interface BuyableItem {
  double getPrice();
class Banana implements BuyableItem {
  double getPrice() {
    return this.getWeight() * this.getUnitPrice();
class Rice implements BuyableItem {
  double getPrice() {
    return this.getCost();
class Register {
  // Handle the item generically.
  //  This way if there's special logic to finding
  //  the price, like it's on special this week, or
  //  it's an item that gets priced by the pound,
  //  the Register class doesn't care.  That implementation
  //  is left to the BuyableItem.
  double scan( BuyableItem item ) {
    return item.getPrice();
public static void main( String[] args ) {
  // Refer to each food by interface
  BuyableItem banana = new Banana();
  BuyableItem rice = new Rice();
  Register reg = new Register();
  double totalCost = 0;
  totalCost += reg.scan( banana );
  totalCost += reg.scan( rice );
  System.out.println( "Total cost is: " + totalCost );
}Interfaces become important when you maintain your code for a while and suddenly discover that you have to add support for a new object.

Similar Messages

  • Why interfaces can not declare static methods?

    Why interfaces can not declare static methods?

    Why are you shouting?
    Is your internet broken?
    [http://www.google.co.uk/search?q=interface+static+methods+java] 2,440,000 hits.

  • Why interface property be default final whats the use of that

    can anybody explain me
    when i declared a variable inside the interface its always public static final.
    why its static and final what the use of theat. its set of rule or it has any reason.

    Sir,
    You do not have much choice:
    From the JLS (9.3):
    "Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields."
    Note from this though that you do not have to explicitly declare a field in an interface as public / static / final if you dont want to - if you leave it out the field is implicitly declared with these attributes.
    So you could wite:
    public interface SirInterface {
      public int HeIsActuallyPublicStaticFinal = 1;
    }

  • Why Interface is necessary in Java?

    Hi,
    we know interface is like a skeleton, that contains only method signatures and variables. Methods must be public, abstract and variables must be public static final.
    simply we are implementing interface and defining all the methods in our class. we can do this without going to interface.
    why we have this interface? please explain me with simple real time example.
    Thanks and Regards,
    Periyasamy

    simply we are implementing interface and defining all
    the methods in our class. we can do this without
    going to interface.Huh?
    why we have this interface? please explain me with
    simple real time example.Do you mean "real-life"?
    Example
    There is no specified implementation type of the return value, and neither should there be one, so it can be easily replaced.

  • Why interfaces why not abstract classes?

    why they are using interfaces concept in JDBC or struts2.0 why not abstract classes?
    thanks in advance.

    user5287726 wrote:
    jverd wrote:
    user5287726 wrote:
    Interfaces are more flexible. For certain definitions of flexible, yes, but not for others.
    A Java class can only inherit one class, but it can implement multiple interfaces.Which has absolutely nothing to do with why JDBC declares interfaces rather than abstract classes.How does your post even attempt to answer the OP's question?OP asked: "why they are using interfaces concept in JDBC or struts2.0 why not abstract classes?" I'm pointing out that your post does not address the question asked. And of course your answer is wrong anyway.
    As for addressing the OP's question, I did that in my first response.

  • Why Interface

    What is the goal of interfaces? I mean that
    I see in some books interfaces provides multiple inheritance.
    But I don't understand this issue. Because you are not implementing
    any code in the interface class. So what is the advantages of using
    interface, just to remember what to code? I think in such a way that
    implement the new class without using an interface. Because what you
    will do with interface, is same amount of work not less. Please
    anyone explain this issue to me. Thanks...

    "Interface" as such a strong concept of Object Oriented Programming Model. In simple English what an interface defines is just a contract {or just you can say "Promise"}. But it gives the freedom of implementation.
    A classic example would be interface IStack, this interface promises the user that it supports "push" and "pop" operation in "Last-In-First-Out" fashion. However the person who implements the stack can used any technique convenient for him, keeping the promise fulfilled. He can use linked list concept, Array concept or any new way he finds, but for user it is just "push" and "pop" operations.
    In real world, interface play's role of "Standard". In a situation where multiple vendors ship libraries, it is good to have common API's for the user of library. User always programs against the interface, by this he gains the advantage of changing the supporting library from 3rd party dynamically.
    Coming to your second point, �Interface provides multiple inheritance� is not the correct way of saying it. In my understanding by using multiple interfaces does not makes any class as inherited from multiple base classes as it would do in C++, in Java context using multiple interface makes a class polymorphic. What I mean here is same instance of class will behave differently by accessing different interfaces implemented by it.
    For example if a class �Person.java� implements two interfaces �Imanager� and �Iclerk� what all it means to us is, we can use {or treat} instance of person either as instance of Imanager or as Iclerk.
    For last part of your question �Why at all interface when I have to code every time?� There is a concept called as programming against Interfaces. What exactly this means is you define most likely behavior of an object and declare that as Interface, by doing so your code becomes stable against changes.
    To make you understand more, consider following algorithm:
    In procedural oriented style:
    CalculateSalary (person x) {
    If (x.type == �Manager�)
    CalculateManagerSalary()
    Else if (x.type = �cleark�)
    CalculateClerkSalary()
    In above code you see that if there is new person category �Technician� then apparently you have to modify you source to add new if condition and also you have to add new method something like CalculateTechniciasalary()and you have to compile you code, make it a library, etc.
    In Object Oriented style:
    Little better but still-
    CalculateSalary (Person x) {
    x.CalculateSalary()
    But the problem in above approach is that we are assuming Person �knows� how to calculate his salary. What I mean by this statement is that you should know the entire API�s provided by the person to work with. In c++ language, making Person as base class of all worker class could solve this. When new worker comes into existence all we have to do is just inherit him from base class Person. Now an important question arises. Is it always necessary to be Person in order to get salary? What if the firm also hires animals like elephant for some work and plans to pay through normal salary procedure? Do we have to have new overloaded method �CalculateSalary (Animal y)�? Or should we inherit Elephant from �Person�?
    In Design pattern style:
    We define the procedure as an interface say for example �ICalculateSalary()�. This interface promises us that �when asked for, I will calculate my Salary for you� and whole method changes to -
    CalculateSalary (ICalculateSalary x) {
    x.CalculateSalary()
    Now an Elephant�s salary can be determined with out having to declare new overloaded method or inheriting from �Person�, same is the case with Pigeon. What all of them have to do is implement the interface �ICalculateSalary� to let others calculate salary with out having to know much about Pigeon or Elephant.
    This should make you comfortable.
    Regards,
    K.V.

  • Why interface for nodes? but class for UI Elements

    Hi Experts,
                    why in wda ,sap has given interface for nodes and elements ,and class for ui Elements.
    Eg. for using nodes they provide if_wd_context _node
          but for input field they provide cl_input_field
    Any Body Having an idea pls revert asap
    Regards
    Sarath

    hi sarath........
                when the node is being shared between 2 views.............. both the views need to access the same node for updating values. so you need an interface between these two.
               where as for elements you need not have any sharing..... and your element id is unique..... so no problem for that.
               where as in nodes... there might be a node of same name in your view as well as your component controller. so you need an interface.
    ---rergards,
      alex b justin

  • Why interfaces cant be protected

    why cant interfaces be declared protected?

    Let's assume for a moment you can have a protected method in an interface.
    That would mean that that method MUST be implemented by something that EXTENDS that interface.
    Only interfaces can EXTEND other interfaces.
    Any class implementing the interface would have to be abstract as it cannot implement the function (it can't even see it after all, as it's protected and thus visible only to things that extend the interface, not to things that implement it).
    Any class subclassing your implementing class cannot be anything other than abstract either of course as it also cannot see the protected method and thus cannot implement it.
    You've now created an entire class tree of abstract classes with no way to ever get an instance of one, hardly useful.
    Even a static method of one of those classes (which you could call) would be unable to use the protected method as it's never implemented and anyway invisible to anything except the interface and any subinterfaces themselves (which the class is definitely not).

  • Why "Interface SQLData of class not found"?

    Could anyone please help me?
    I use JDK1.2.2 with Oracle 8.1.5.
    I wanna try the example of SQLData Implementation here: http://technet.oracle.com/doc/oracle8i_816/java.816/a81354/samapp6.htm#1016717
    But I just got the error message keeping saying that "Interface SQLData od class EmployeeObj() not found".
    What's up with it?
    Any response is appreciated. :)

    Hello Carlos
    It is possible that something went wrong when you imported the class into your TEST system.
    The error message could imply that the corresponding record is missing from table TRDIR.
    I would recommend to make a small change of the class in your DEV system (e.g. change description) and transport the entire class gain into the TEST system (context menu within SE80 -> create Transport Entry for entire class).
    After the import you should go to SE24 and activate the class to see if everything is ok.
    Regards
      Uwe

  • Why JNDI is called an Interface?

    Why JNDI is called as Java Naming and Directory Interface, question is why
    interface ? when it is not a interface ?

    It is an interface because it is defined as an abstract set of APIs, not actually implementation. The actually implementation is done by service providers.
    Defining an abstract set of APIs without actually implementation can isolate the implemenation of service provide and client application code, thus make them more independently from each other. i.e, a client application would not need to know what changes made by any particular vendor.
    Hope this helps.

  • Why only public methods in interfaces?

    Howdy all,
    I'm wondering if someone can shed some light on why Java doesn't allow interfaces to declare non-public methods.
    Ideally, I'd like to do something like this:
    public Interface Foo {
      protected void setFooProperty(int);
      public int getFooProperty();
    public Interface Goo {
      protected void makeGooey(boolean);
      public boolean isGooey();
    public class A implements Foo
    public class B implements Goo
    public class C implements Foo, GooI don't see any technical reason why interfaces must be restricted to declaring public methods only, but it seems too arbitrary to have been done without reason. Any ideas?

    I don't think that is a good idea to put non-public methods in public interfaces. But I beleive that's a good idea to have protected (or friendly) interfaces to be used only in package scope. It could help a lot some projets defining a second level of data exposure of an object so that developers of that package could have more information that others users from outside the package have that are interesting to develop better algorithm that work with that data. In this way, we can defien thre levels of that access: The lower is the package user, that can see the minimum that's possible, above him we have the package developer that don't work directly with the data, but needs some deep access to it to do cool stuff, and finally we have the guy that is doing the object that deals directly with the data (and encapsulate it).
    In this way we can decouple a little the data from the algorithms that work on it, put between them an interface that standarize the access to the data in an intermediate level.
    Hope you are able to understand what I wrote (my english isn't so good!).
    RGB

  • Why does interfaces allow class definitions within them

    Can anybody explain why interfaces can contain class definitions.

    Saish wrote:
    It does somewhat adulterate the idea that interfaces and implementations should be separate. I would find it more useful if the class that you declare could be something other than public. That way, you could expose an interface, a factory (which would be public) and then have all the implementations private in the same file. A client would only see the factory and the interface (granted, one could achieve the same effect with non public classes in their own source files all in the same package). But to require that member types within the interface be public, that really makes little sense to me.agreed - this limitation is quite annoying. Forces me to use extra level of nesting to work around it:
    // see also: http://forums.sun.com/thread.jspa?messageID=10938789#10938789
    public interface MyInfo {
      public MyStatus getMyStatus();
      public static interface MyStatus { } // MyStatus
      public static class Factory {
        public static MyStatus newMyInfo() {
          return new MyInfo() {
            public MyStatus getMyStatus() {
              return new Innards.MyStatusImpl();
      } // Factory
      // IMPL NOTE purpose of this class is to keep implementation details inside
      public final /* IMPL NOTE subclassing prohibited */ static class Innards {
        private Innards() {}  /* IMPL NOTE instantiation prohibited */
        private static class MyStatusImpl implements MyStatus { } // MyStatusImpl
      } // Innards
    } // MyInfo

  • Why is interface required

    Friends can u please explain me why Interface is required.I read few explanation and I am having problems understanding it .
    thanks
    Manohar

    For example you can specify interface like this:
    public interface Namer {
    public String getName();
    Then you can implement class with code like this:
    public void printName(Namer nm){
    System.out.println(nm.getName());
    Then you can tell your friends 1,2,3:
    1 implement for me Namer to take name from net
    2 implement for me Namer to take name from dastabase
    3 implement for me Namer to take name from flat file
    And when they provide you with this implementation, every class which implements Namer interface can be passed to your printName method.
    This is very syntetic example. In short: interfaces provides some abstraction, they allow you to specify inter-object communication abstracting from implementation details. In my opinion greatest set of interfaces is JDBC.

  • Why are all methods virtual???

    class Base
         public Base()
              System.out.println("Calling f() from base class ...");
              f();
              return;
         public void f()
              System.out.println("Base class function called!");
              return;
    class Derived extends Base
         public Derived()
              System.out.println("Calling f() from derived class ...");
              f();
              return;
         public void f()
              System.out.println("Derived class function called!");
              return;
         public static void main(String args[])
              new Derived();
              return;
    }The problem in this: the call to f() from the Base class calls the Derived class method. I want it to call the Base class method. How do I do this?
    Ravi

    Sorry, I cant explain the circumstances under which I
    encountered this problem without explaining a whole
    lot about my product. But I cant make it a private
    method because I need to be able to call it from
    outside the package. I found a workaround for my
    problem by putting a call to super.f() in the derived
    class. But I really wonder why the makers of Java
    chose to make it this way!
    RaviIf you can't explain your problem then don't post your questions here. It's not like a small post on a forum board will cause your IP any damage.
    The design of OOP is that if you override a method in a subclass of an object, the reason for doing so is that you are add/changing functionality of that method. If you don't need to add/change functionality of a method then don't override it. Polymorphism ensures that no matter what type of object the compiler thinks you are reffering to, at runtime you will call the correct method of the type of object you encounter then. This is why interfaces work. calling the super class to complete processing of a method is not a hack, or a design problem it's the way to do it. If the class that you are extending changes private data structures in a method, and you override that method, unless you are doing a radical change to the class, you probably need to call the super method to ensure that the proper changes are made.

  • Is an audio interface really necessary?

    Ok, right now I have my condenser mic hooked up to a phantom power and from the phantom power to the computer. All my recordings come out clear and loud. But my friend told me that if I get an audio interface, my recordings will sound much better. Well is it true? What are the benefits of an audio interface?
    thanks

    I actually use a variety of interfaces. Yesterday I spent the day with one from M-Audio and, while not as good sounding as the RME in my sig, the results were surprisingly good.
    While there are a number of technical reasons why interfaces will sound better than going into the computer directly, aside from the technical mumbo jumbo, I do find a big jump in sound quality using an interface vs. a direct input, and not simply the difference between one flavor preamp and another.
    Obviously, there are interfaces, and then there are interfaces! But even so, I've yet to use any interface that hasn't worked noticeably better than plugging directly into the computer.
    That said, if someone is just starting out and wants to plug and play, and is more than happy with the quality of the computer's inputs, then they're wasting their money buying anything else. No one should buy anything they don't want or need!
    But if someone is striving for better sound quality than what comes with the computer, the fact that interfaces add obvious flexibility shouldn't shroud the fact that they also improve sound quality under the hood.
    kbeartx does make an excellent point, one of two that frequently degrade conversations about gear. Of course experience is all important! And the other: "it's all about the music," as if discussing equipment suggests otherwise. Still, equipment, and discussing it, has a value. Equipment and experience are not mutually exclusive.
    It's like surgeons speaking about scalpels. An experienced surgeon will do a better job with a steak knife than an inexperienced surgeon will do with a finely-honed scalpel. Still, no one would denigrate any surgeon for seeking the best tool available.
    That's all this is.
    Inifinity239 has a steak knife and is wondering if a scalpel works better. As someone who has used both (to continue this now very tortured metaphor )... I would say of course!

Maybe you are looking for

  • Some Windows 8.1 Modern Apps will not open

    Hi We have been using Windows 8 for 2 years, however since a recent migration to a global AD system multiple modern apps have stopped working. Mail, Store, Camera etc all work - however as an example Yammer, Weave, Facebook, Ebay etc all go to open,

  • MM Pricing procedure - Condition type post to different GL account in MAP

    Hi All, We have a requirement for posting intercompany Stock transfer between Company A and B, and the transfer price will be Moving Average Price (say $ 100) + Mark up (say 25% i.e., 25) of supplying plant. Created a new PO pricing procedure, and cr

  • How can I find a charger for my iPhone 5?

    I recently came back off of a trip and I misplaced my Iphone 5 charger. Is there any possible way I can find one anywhere or find an adapter?

  • 17" Studio ADC display to Thunderbolt

    I have an old PowerMac G4 that I use with the ADC display. Well I will soon be aquiring a new 13" MacBook air. I want to know if I can use  a series of adapters to hook up my old ADC display to my new MacBook w/ Thunderbolt. What do I need?

  • UK requirements on VAT

    Hi Experts, I'm currently working for a UK based company which has to be UK compliant for VAT  The currency settings for the problematic company code is EUR as local currency. The reason therefore is that lots of its vendors send invoices in EUR. Nev