Java Workshop 7

  • fixed abstrack method takes prameter as an varargs
  • improuve namve of interface and abstract method more general
  • eventually, getProperty method deosn’t take any parameters for better utilization

@FunctionalInterface
public interface ShapeProperty { 
    double getProperty(double... d);  // varargs takes parameter as an array
}

Traditional way to define functional interface’s method

public class Rectangle extends Parallelogram { 
   private ShapeProperty property = new ShapeProperty() {  
		@Override
		public double getProperty(double... d) {
			return d[0] * d[1];
		}
	};

	public Rectangle(double width, double height) throws ParallelogramException{
			super(width, height); 
	}

	public ShapeProperty getArea(){
	    return property;
    }

	@Override
	public String toString(){ //return string 
		return "Rectangle {w=" + getWidth() + ", h=" + getHeight() + "}" +
				" perimeter = " + perimeter() + " area = " + property.getProperty(getWidth(), getHeight());
	}
}


Lambda Expression to define functional interface’s method

public class Rectangle extends Parallelogram { 

    private ShapeProperty property = wh -> wh[0] * wh[1];

	public Rectangle(double width, double height) throws ParallelogramException{
			super(width, height); 
	}

	public ShapeProperty getArea(){
	    return property;
    }

	@Override
	public String toString(){ //return string 
		return "Rectangle {w=" + getWidth() + ", h=" + getHeight() + "}" +
				" perimeter = " + perimeter() + " area = " + property.getProperty(getWidth(), getHeight());
	}
}


Best Solution for functional interface

@FunctionalInterface
public interface ShapeProperty { 
    double getProperty(); 
}
public class Rectangle extends Parallelogram { 

    private ShapeProperty property = () -> getWidth() * getHeight();

	public Rectangle(double width, double height) throws ParallelogramException{
			super(width, height); 
	}

	public ShapeProperty getArea(){
	    return property;
    }

	@Override
	public String toString(){ //return string 
		return "Rectangle {w=" + getWidth() + ", h=" + getHeight() + "}" +
				" perimeter = " + perimeter() + " area = " + property.getProperty();
	}
}