加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java接口应该只包含getter吗?

发布时间:2020-12-15 01:07:20 所属栏目:Java 来源:网络整理
导读:我有一些关于界面使用的一般问题: 为每个对象类创建接口有什么好处? 接口应该只包含getter方法吗? 为什么不也是二传手呢? 为什么我要为每个对象类创建一个接口?它会在JUnit测试中为我服务吗? 例如 : public interface Animal { public getVoice(); pu

我有一些关于界面使用的一般问题:

>为每个对象类创建接口有什么好处?
>接口应该只包含’getter’方法吗?
>为什么不也是二传手呢?
>为什么我要为每个对象类创建一个接口?它会在JUnit测试中为我服务吗?

例如 :

    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;
  }

}

谢谢

最佳答案

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

没有任何优势.这不是Interfaces的用途.

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

只要它是方法,接口就不关心它们的功能行为.

Why should I create for each object class an interface?

同样,这不是界面的目的.将其视为冗余.

如果您了解interfaces是什么,您将意识到它们的正确用法

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读