Java接口的意义何在?

时间:2019-05-09 17:53:12

标签: java interface abstract

看一下带有接口的这段代码,我可以理解这是合乎逻辑的,而且很有帮助,但是我看不到这会发生什么变化?如果您只是删除了动物界面,一切仍将以完全相同的方式工作,不是吗?界面的意义是什么?

// Interface
interface Animal {
  public void animalSound(); // interface method (does not have a body)
  public void sleep(); // interface method (does not have a body)
}

// Pig "implements" the Animal interface
class Pig implements Animal {
  public void animalSound() {
    // The body of animalSound() is provided here
    System.out.println("The pig says: wee wee");
  }
  public void sleep() {
    // The body of sleep() is provided here
    System.out.println("Zzz");
  }
}

class MyMainClass {
  public static void main(String[] args) {
    Pig myPig = new Pig();  // Create a Pig object
    myPig.animalSound();
    myPig.sleep();
  }
}

0 个答案:

没有答案