I am learning lambda expressions and functional interfaces. We can directly write an implementation of the interface by the lambda expression. So I think, it could be the alternative for polymorphism.
I have some code using polymorphism,
interface Drawable {
public void draw();
}
class Shape {
protected String name;
public Shape(String name) {
this.name = name;
}
}
class Rectangle extends Shape implements Drawable {
public Rectangle(String name) {
super(name);
}
@Override
public void draw() {
System.out.println("I am "+this.name);
System.out.println("Drawing rectangle with 2 equal sides.");
}
}
class Square extends Shape implements Drawable {
public Square(String name) {
super(name);
}
@Override
public void draw() {
System.out.println("I am "+this.name);
System.out.println("Drawing square with 4 equal sides.");
}
}
public class DrawShape {
public static void main(String ar[]) {
Drawable rectangle = new Rectangle("Rectangle");
rectangle.draw();
Drawable square = new Square("Square");
square.draw();
}
}
I have written above code using lambda expressions and functional interface,
@FunctionalInterface
interface Drawable {
public void draw();
}
class Shape {
private String name;
public Shape(String name) {
this.name = name;
}
public void draw(Drawable d1) {
System.out.println("I am "+this.name);
d1.draw();
}
}
public class DrawShape {
public static void main(String[] args) {
Shape s1 = new Shape("Rectangle");
Drawable rectangle = () -> System.out.println("Drawing rectangle with 2 equal sides.");
s1.draw(rectangle);
Shape s2 = new Shape("Square");
Drawable sqaure = () -> System.out.println("Drawing square with 4 equal sides.");
s2.draw(sqaure);
}
}
Which is the better approach? What about other aspects like code reusability, code maintenance and modification, coupling and cohesion etc for lambda?