Merge pull request #10769 from vikasrajput6035/BAEL-4936

BAEL-4936: Completed article Abstract class vs Interface with default method
This commit is contained in:
Greg 2021-06-14 12:02:05 -04:00 committed by GitHub
commit 3bf486a4dd
5 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,14 @@
package com.baeldung.interfaceVsAbstractClass;
public class ChidlCircleInterfaceImpl implements CircleInterface {
private String color;
@Override
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaceVsAbstractClass;
public class ChildCircleClass extends CircleClass {
}

View File

@ -0,0 +1,23 @@
package com.baeldung.interfaceVsAbstractClass;
import java.util.Arrays;
import java.util.List;
public abstract class CircleClass {
private String color;
private List<String> allowedColors = Arrays.asList("RED", "GREEN", "BLUE");
public boolean isValid() {
return allowedColors.contains(getColor());
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.interfaceVsAbstractClass;
import java.util.Arrays;
import java.util.List;
public interface CircleInterface {
List<String> allowedColors = Arrays.asList("RED", "GREEN", "BLUE");
String getColor();
public default boolean isValid() {
return allowedColors.contains(getColor());
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.interfaceVsAbstractClass;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class InterfaceVsAbstractClassUnitTest {
@Test
public void givenAbstractClass_whenValidCircleUsed_thenPass() {
CircleClass redCircle = new ChildCircleClass();
redCircle.setColor("RED");
assertTrue(redCircle.isValid());
}
@Test
public void givenInterface_whenValidCircleWithoutStateUsed_thenPass() {
ChidlCircleInterfaceImpl redCircleWithoutState = new ChidlCircleInterfaceImpl();
redCircleWithoutState.setColor("RED");
assertTrue(redCircleWithoutState.isValid());
}
}