I have some general questions regarding interface usage:
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With