3

Code 1:

public class User1 implements MyInterface
{
    @Override
    public void doCalculation() { }
}

public class User2 implements MyInterface
{
    @Override
    public void doCalculation() { }
}

interface MyInterface
{
    public void doCalculation();
}

Code 2:

public class User1
{
    public void doCalculation() { }
}

public class User2
{
    public void doCalculation() { }
}

Here in my Code 1 I have MyInterface which has an empty method doCalculation(). That doCalculation() is used by user1 and user2 by implementing MyInterface.

Where as in my Code 2 I have two different classes with defined doCalculation() method.

In both the cases code1 and code2 I myself have to write the implementation. My method doCalculation() is just an empty method.

So what is the use of MyInterface here?

  1. It only provides me the method name or skeleton (is that the only advantage of interface)?

  2. Or else would I save any memory while using MyInterface?

  3. Is that, it only provides the empty method for an class which implements it, then why not I define it by myself as I have done in my code2.

  4. More than that is there any more advantage on using an interface.

Ravi Chandran
  • 131
  • 2
  • 10
  • 2
    Hi, I´ve edited your post, but you have misspelled `doCalculation()` a lot as `doClaculation()`. Can you correct this? I don´t want to change your code syntactically. – John Willemse Jun 25 '13 at 10:57
  • 1
    @JohnWillemse: I don't know. For some reason I like "Claculation". It has a certain ring to it. To the original poster, get a book on "Design Patterns" and then you'll better see and understand the beauty and power of interfaces. It allows for "plug in" injectable code, as well as mockable and testable code. – Hovercraft Full Of Eels Jun 25 '13 at 10:58
  • 1
    possible duplicate of [Should you always Code To Interfaces In Java](http://stackoverflow.com/questions/3194278/should-you-always-code-to-interfaces-in-java) and *many* other interface questions. – Hovercraft Full Of Eels Jun 25 '13 at 11:05
  • 2
    Visit this link http://stackoverflow.com/questions/6533147/interface-advantages-in-java – Gaurav Manral Jun 25 '13 at 11:25
  • Oh Thanks i think i am learning very slow..... but will do keep learning thanks for your reply..... – Ravi Chandran Jun 25 '13 at 15:53

9 Answers9

3

Interfaces are used a lot because they are basically a blueprint of what your class should be able to do.

For example, if you are writing a video game with characters, you can have an interface that holds all the methods that a character should have.

For example

public interface Character {
    public void doAction();
}

And you have 2 characters, for example an ally and an enemy.

public class Ally implements Character {
    public void doAction() {
        System.out.println("Defend");
    }
}

public class Enemy implements Character {
    public void doAction() {
        System.out.println("Attack");
    }
}

As you can see, both classes implement the interface, but they have different actions. Now you can create a character which implements your interface and have it perform its action. Depending on if it's an enemy or an ally, it'll perform a different action.

public Character ally = new Ally();
public Character enemy = new Enemy();

And in your main program, you can create a method that accepts any object that implements your interface and have it perform it's action without knowing what kind of character it is.

void characterDoAction(Character char) {
    char.doAction();
}

If you would give ally to this method, the output would be:

Defend

If you would give enemy to this method, the output would be:

Attack

I hope this was a good enough example to help you understand the benefits of using interfaces.

JREN
  • 3,572
  • 3
  • 27
  • 45
2

There are a lot of advantages of interface driven programming.

What does "program to interfaces, not implementations" mean?

Basically you are defining a contract in an interface and all the classes which implement the interface have to abide by the contract.

Answers to your queries:

1.It only provides me the method name or skeleton (is that the only advantage of interface)?

--> Its not just about providing the method name but also defining what the class implementing the interface can do.

2.Or else would I save any memory while using MyInterface?

--> Nothing to do with the memory

  1. Is that, it only provides the empty method for an class which implements it, then why not I define it by myself as I have done in my code2. --> see the advantages of interface driven programming.

4.More than that is there any more advantage on using an interface. --> Plenty,specially dependency injection , mocking , unit testing etc.

Community
  • 1
  • 1
sidshu
  • 315
  • 4
  • 13
  • sidshu please correct me if i am wrong... your answer for the 1st question . what can an empty method do when i implement from an interface, what u tell is just based on the name of the method(adjective) and not its implementation. – Ravi Chandran Jun 25 '13 at 16:21
  • (i.e by just looking at the name of the interface or the method in the interface we can have a conclusion that this interface is purposely for some activity ) – Ravi Chandran Jun 25 '13 at 16:28
  • @RaviChandran I understand what you mean and you can implement an interface and define an empty method or method returning null but then it will be a bad practice to follow. So e.g. if you have an interface Bird with method fly() and you create an implementation class sparrow and create an empty method implementation . The code can be syntactically correct but it wont make any sense , hence a bad practice. – sidshu Jun 26 '13 at 10:22
  • i agree with your comment, if i use the interface for that only it is waste of implementing it........ but could u add more details which place is apt and where can i use it..... – Ravi Chandran Jun 26 '13 at 11:44
1

A very good explanation can be found here when-best-to-use-an-interface-in-java. It really depends on what you're building and how much scalability, code duplications, etc you want/don't want to have.

Community
  • 1
  • 1
Tala
  • 8,888
  • 5
  • 34
  • 38
1

Many classes use interfaces to perform some function, relying on other programmers to implement that interface respecting the contract that an interface govern. Such classes are, for example, KeyListeners, MouseListeners, Runnable, etc.

For example: JVM knows what to do with a Thread, how to start it, stop it, manipulate it, but it does not know what your Thread should do, so you have to implement the Runnable interface.


Interfaces offer you a level of abstraction which can be leveraged in other classes. For example, if you have an interface called GemetricFigure, in a class that prints girth of a GeometricFigure you could iterate over a list of all GeometricFigures like:

public class Canvas {

   private List<GeometricFigure> figures;

   public void print() {
       for (GeometricFigure figure : figure) {
           System.out.println(figure.getGirth());
       }
   }

}

And if the GeometricFigure has only that method:

public interface GeometricFigure {

    public Double getGirth();

}

You wouldn't care how Square or Circle implement that interface. Otherwise, if there were no interface, you could not have a list of GeometricFigures in Canvas, but a list for every figure type.

darijan
  • 9,725
  • 25
  • 38
  • its really interesting darijan... can you be more clear with what the figure.getGirth() prints....... little bit make clear on your code.... – Ravi Chandran Jun 25 '13 at 16:16
  • @RaviChandran Take a look at this example I just wrote. It's runnable and has comments so it will be much more clear to you: http://pastebin.com/5kmLgVVK – darijan Jun 25 '13 at 16:42
0

Interface is like a contract that your implementing class should satisfy. Usually, you will write an interface and make all your other class's implement it with their own implementation.

Example:

interface IExporter {
    public void export();
}

public class PDFExport implements IExporter {
    public void export(){
    //code for PDF Exporting
    }
}

public class XLSExport implements IExporter {
    public void export(){
    //code for XLS Exporting
    }
}

public class DOCExport implements IExporter {
    public void export(){
    //code for DOC Exporting
    }
}
JREN
  • 3,572
  • 3
  • 27
  • 45
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

With the interface approach you can do the following:

List<MyInterface> list = new ArrayList<MyInterface();

list.add(new User1());
list.add(new User2());

for(MyInterface myInterface : list) {
    myInterface.doClaculation()
}

This does not work with the second approach. Interfaces are for the code that use your classes - not for your classes themselves.

Marco Forberg
  • 2,634
  • 5
  • 22
  • 33
0

You can use interfaces in many cases. Also the situation you describes: You needn't to know, which implementation you have.

For example you have anywhere in your code a method, that returns the current singed in user even you don't know if it is User1 or User2 implementation, however that both of them can calculate something by method doCalculation. I add a really dummy example of that situation:

public void dummyExampleCalculation() {

   getCurrentUser().doCalculation();

}

public MyInterface getCurrentUser() {

   if(...) {
      return new User1();
   } else {
      return new User2();
   }

}
Martin Strejc
  • 4,307
  • 2
  • 23
  • 38
0

That is what Object Oriented Programming is all about.Interfaces are used to perform polymorphism. You said, you can implementations in code2 for both the classes, what if in future there is user3 who needs to doCalculation. You can just implement that interface and write your calculation in your own form.

When you want to provide a basic functionality to all your users abstract classes comes into picture where in you can declare an abstract method do calculation and provide implementation of that basic functionalities which then each user will extend and can doCalculation in their own way.

roger_that
  • 9,493
  • 18
  • 66
  • 102
0

Interface in Java is used to impose an implementation rule on classes. That means you can declare the signature of functions in interfaces and then implement these function in various classes by exactly following the function signature.

You can see a clear and realistic example on the following webpage

http://www.csnotes32.com/2014/10/interface-in-java.html

ANAND
  • 11
  • 2