【问题标题】:What is the purpose of using interface when its methods don't have any implementation we have to override them every time?当接口的方法没有任何实现我们每次都必须重写它们时,使用接口的目的是什么?
【发布时间】:2018-07-20 14:44:09
【问题描述】:
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();
}
}
【问题讨论】:
标签:
java
interface
abstract-class
【解决方案1】:
当您有多个实现相同接口的类时,这很有用。它允许使用多态性。您还可以使用抽象类来实现一些常见的功能。从 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
}
}
}