From 692f3b201a8a081664963b039a27ea41f3e5a318 Mon Sep 17 00:00:00 2001 From: michaelin007 Date: Sun, 3 Dec 2023 07:19:26 +0000 Subject: [PATCH] Final Static Variables in Java --- .../java/com/baeldung/finalstatic/Bike.java | 14 ++++++++++ .../baeldung/finalstatic/BikeUnitTest.java | 28 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java create mode 100644 core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java diff --git a/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java new file mode 100644 index 0000000000..6467ccc395 --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/main/java/com/baeldung/finalstatic/Bike.java @@ -0,0 +1,14 @@ +package com.baeldung.finalstatic; + +import java.util.HashMap; + +public class Bike { + public static final int TIRE = 2; + public static final int PEDAL; + public static final HashMap PART = new HashMap<>(); + + static { + PEDAL = 5; + } + +} diff --git a/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java new file mode 100644 index 0000000000..bd7f578a9a --- /dev/null +++ b/core-java-modules/core-java-lang-6/src/test/java/com/baeldung/finalstatic/BikeUnitTest.java @@ -0,0 +1,28 @@ +package com.baeldung.finalstatic; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class BikeUnitTest { + + @Test + void givenTireConstantSetUponDeclaration_whenGetTire_thenReturnTwo() { + assertEquals(2, Bike.TIRE); + } + + @Test + void givenPedalConstantSetByStaticBlock_whenGetPedal_thenReturnFive() { + assertEquals(5, Bike.PEDAL); + } + + @Test + void givenPartConstantObject_whenObjectStateChanged_thenCorrect() { + Bike.PART.put("seat", 1); + assertEquals(1, Bike.PART.get("seat")); + + Bike.PART.put("seat", 5); + assertEquals(5, Bike.PART.get("seat")); + } + +} \ No newline at end of file