Reputation: 65
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();
}
}
Upvotes: 0
Views: 47
Reputation: 8758
This is useful when you have several classes implementing same interface. It allows to use polymorphism. You can also use abstract classes to implement some common functionality. And starting Java 8 you can provide default implementation in interfaces themselves.
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
}
}
}
Upvotes: 2