6

I have some general questions regarding interface usage:

  1. What is the advantages in creating interface for each object class ?
  2. Should interface only contains 'getter' methods?
  3. Why not also the setter?
  4. Why should I create for each object class an interface? Will it served me in the JUnit tests?

For example :

    public interface Animal {
      public getVoice();
      public String getName();
    }

public class Dog implements Animal {
   private String name;

   public getVoice(){
      System.out.println("Brrr");
   }
   public String getName(){
      return this.name;
   }
   public void setName(String name){
      this.name = name;
  }

}

Thanks

2
  • You're asking at least three questions here. Would you mind narrowing it down to one that can be concisely answered? Commented May 25, 2016 at 16:27
  • Unit tests test concrete implementations, they do need to test the "interface" (in a broader sense) of a class but not necessarily the interface: stackoverflow.com/questions/10937763/… Commented May 25, 2016 at 16:32

2 Answers 2

9

What is the advantages in creating interface for each object class ?

There is no advantage at all. That is not what Interfaces are for.

Should interface only contains 'getter' methods? Why not also the setter?

As long as it is method, interfaces doesn't care about their functional behaviour.

Why should I create for each object class an interface?

Again, that is not the purpose of interface. Consider that as Redundant.

If you understand what are interfaces, you'll realize their correct usage

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler.

Sign up to request clarification or add additional context in comments.

Comments

3

Interfaces are meant to describe contracts. Either for inner use in the application, by providing an abstraction over several implementations, or maybe to provide them to external entities for them to implement.

There can be any amount of methods in the interface, the purpose of them is to enforce their implementation on the implementing classes, so the contract is maintained.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.