当接口的方法没有任何实现而我们每次都必须重写它们时,使用接口的目的是什么?

时间:2018-07-20 14:44:09

标签: java interface abstract-class

interface Interface {
    void m1();
}

class Child implements Interface {
    public void m1() {
        System.out.println("Child.....");
    }
}

public class InterfaceDemo {
    public static void main(String[] args) {
        Child c = new Child();
        c.m1();
        Interface i = new Child();
        i.m1();
    }
}   

1 个答案:

答案 0 :(得分:2)

当您有多个实现相同接口的类时,这很有用。它允许使用多态性。您还可以使用抽象类来实现一些常用功能。从Java 8开始,您可以在接口本身中提供默认实现。

interface Shape {
  void draw();
  double getSquare();
}

class Circle implements Shape {
  public void draw() {}
  public double getSquare() {return 4 * PI * r * r;}
}

class Square implements Shape {
  public void draw() {}
  public double getSquare() {return w * w;}
}

class Main {
  public static void main(String[] args) {
    for (Shape s : Arrays.asList(new Circle(), new Square(), new Square(), new Circle())) {
      s.draw(); //draw a shape. In this case it doesn't matter what exact shapes are in collection since it is possible to call interface method
    }
  } 
}