Static ref non static (#15571)

* [rm-char-in-other-str] BAEL-7355 Remove characters from a string that are present in a second string

* [rm-char-in-other-str] shorten the package name

* [static-ref-non-static] static context ref non-static memebers
This commit is contained in:
Kai Yuan 2024-01-12 03:22:00 +01:00 committed by GitHub
parent 9b6a2a0236
commit edeee5a571
1 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,60 @@
package com.baeldung.staticnonstatic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class ToolBox {
private String concat(String str1, String str2) {
return str1 + str2;
}
private static String concatStatic(String str1, String str2) {
return str1 + str2;
}
static String joinTwoStrings(String str1, String str2) {
// return concat(str1, str2); //<-- compilation error
return concatStatic(str1, str2);
}
static String creatingInstanceJoinTwoStrings(String str1, String str2) {
ToolBox toolBox = new ToolBox();
return toolBox.concat(str1, str2);
}
String instanceJoinTwoStrings(String str1, String str2) {
return concat(str1, str2);
}
String instanceCallStaticJoinTwoStrings(String str1, String str2) {
return concatStatic(str1, str2);
}
}
public class StaticReferenceNonStaticMethodUnitTest {
@Test
void whenCallingStaticMethodFromStaticContext_thenGetExpectedResult() {
assertEquals("ab", ToolBox.joinTwoStrings("a", "b"));
}
@Test
void whenCallingInstanceMethodByCreatingAnInstance_thenGetExpectedResult() {
assertEquals("ab", ToolBox.creatingInstanceJoinTwoStrings("a", "b"));
}
@Test
void whenCallingInstanceMethodFromAnInstance_thenGetExpectedResult() {
ToolBox toolBox = new ToolBox();
assertEquals("ab", toolBox.instanceJoinTwoStrings("a", "b"));
}
@Test
void whenCallingStaticMethodFromAnInstance_thenGetExpectedResult() {
ToolBox toolBox = new ToolBox();
assertEquals("ab", toolBox.instanceCallStaticJoinTwoStrings("a", "b"));
}
}