Computer Programming
Java Programming
Pierre-Auguste Renoir

Why do you use an interface for implementing methods Isn't it just extra work?

Top Answer
User Avatar
Wiki User
April 10, 2009 7:47PM

== == By creating an interface, the programmer creates a method to handle objects that implement it in a generic way. An example of this would be the Runnable interface in Java. If the programmer is given a Runnable object, they do not need to know what that object really is to be able to call the run method. Ex.

public void startThreads(ArrayList threads){ for(Runnable r : threads) (new Thread(r)).start();

} The objects in the ArrayList threads may be anything at all, but because they all implement the Runnable interface, it is possible to execute their run method generically, in this case encapsulating it in a Thread object and starting that Thread.

Answer:

In Java, it will not support a concept like "subclass having more than one superclass" ex: class subclass extends superclass1,superclass2 so, to implement this concept , Java introduced a new methodology called "interface", interface is also a class , but it has only function declarations having no function definitions. thereby, we can inherit more than one interfaces through "implements" key word. For an interface we cont declare an object,but, we have an alternative ,through assigning an object of a class which implements that interface. ex: interfacename iobj; subclass sobj=new subclass(); iobj=sobj; iobj.funame1(); iobj.funame2(); iobj.funame3(); note: these three funames are the member functions of the above interface, and subclass has to give the definition for them, dynamic binding...right! Apart from these already three declared functions, we don't give the reference to the iobj, ok! the other explanation for implements is, giving definition for a member function, today or in future ,which is declared in past.