Bal 4152 covariant return type (#9561)

* BAEL-4152: added covariant return type material

* BAEL-4152: covariant return type article related code is moved to another package
This commit is contained in:
Gergo Petrik 2020-06-24 08:16:17 +02:00 committed by GitHub
parent edc392ebcf
commit ac6390da3b
3 changed files with 65 additions and 0 deletions

View File

@ -0,0 +1,8 @@
package com.baeldung.covariance;
public class IntegerProducer extends Producer {
@Override
public Integer produce(String input) {
return Integer.parseInt(input);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.covariance;
public class Producer {
public Object produce(String input) {
Object result = input.toLowerCase();
return result;
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.covariance;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class CovariantProducersUnitTest {
@Test
public void whenInputIsArbitrary_thenProducerProducesString() {
String arbitraryInput = "just a random text";
Producer producer = new Producer();
Object objectOutput = producer.produce(arbitraryInput);
assertEquals(arbitraryInput, objectOutput);
assertEquals(String.class, objectOutput.getClass());
}
@Test
public void whenInputIsArbitrary_thenIntegerProducerFails() {
String arbitraryInput = "just a random text";
Producer producer = new IntegerProducer();
assertThrows(NumberFormatException.class, () -> producer.produce(arbitraryInput));
}
@Test
public void whenInputIsSupported_thenProducerCreatesInteger() {
String integerAsString = "42";
Producer producer = new IntegerProducer();
Object result = producer.produce(integerAsString);
assertEquals(Integer.class, result.getClass());
assertEquals(Integer.parseInt(integerAsString), result);
}
@Test
public void whenInputIsSupported_thenIntegerProducerCreatesIntegerWithoutCasting() {
String integerAsString = "42";
IntegerProducer producer = new IntegerProducer();
Integer result = producer.produce(integerAsString);
assertEquals(Integer.parseInt(integerAsString), result);
}
}