BAEL-4936: Completed artcile Abstract class with default method vs interface

This commit is contained in:
Vikas Ramsingh Rajput 2021-05-16 09:32:20 +05:30
parent 44fd4f91b4
commit 3f1778907a
5 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,13 @@
package com.baeldung.interfaceVsAbstractClass;
public class ChidlCircleInterfaceImpl implements CircleInterface {
private String color;
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,27 @@
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() {
if (allowedColors.contains(getColor())) {
return true;
} else {
return false;
}
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}

View File

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

View File

@ -0,0 +1,36 @@
package com.baeldung.interfaceVsAbstractClass;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class InterfaceVsAbstractClassUnitTest {
@Test
public void givenAbstractClass_whenValidCircleUsedThenPass() {
CircleClass redCircle = new ChildCircleClass();
redCircle.setColor("RED");
assertTrue(redCircle.isValid());
}
@Test
public void givenAbstractClass_whenInvalidCircleUsedThenFail() {
CircleClass redCircle = new ChildCircleClass();
redCircle.setColor("WHITE");
assertFalse(redCircle.isValid());
}
@Test
public void givenInterface_whenValidCircleWithoutStateUsedThenPass() {
ChidlCircleInterfaceImpl redCircleWithoutState = new ChidlCircleInterfaceImpl();
redCircleWithoutState.setColor("RED");
assertTrue(redCircleWithoutState.isValid(redCircleWithoutState.getColor()));
}
@Test
public void givenInterface_whenInvalidCircleWithoutStateUsedThenFail() {
ChidlCircleInterfaceImpl redCircleWithoutState = new ChidlCircleInterfaceImpl();
redCircleWithoutState.setColor("WHITE");
assertFalse(redCircleWithoutState.isValid(redCircleWithoutState.getColor()));
}
}