From edeee5a5710ea5b653227a9b964b473417f7a45e Mon Sep 17 00:00:00 2001 From: Kai Yuan Date: Fri, 12 Jan 2024 03:22:00 +0100 Subject: [PATCH] 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 --- ...taticReferenceNonStaticMethodUnitTest.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticnonstatic/StaticReferenceNonStaticMethodUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticnonstatic/StaticReferenceNonStaticMethodUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticnonstatic/StaticReferenceNonStaticMethodUnitTest.java new file mode 100644 index 0000000000..11b8a5b87b --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/staticnonstatic/StaticReferenceNonStaticMethodUnitTest.java @@ -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")); + } + +} \ No newline at end of file