Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Java interface only contain getters?

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

like image 413
userit1985 Avatar asked May 25 '16 16:05

userit1985


2 Answers

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.

like image 156
Suresh Atta Avatar answered Oct 17 '22 00:10

Suresh Atta


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.

like image 32
Hilario Fernandes Avatar answered Oct 17 '22 00:10

Hilario Fernandes