<!-- markdownlint-disable no-inline-html --> <style> @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;600&family=Lato:wght@400;700&display=swap'); :root { --red: #bf616a; --orange: #cb6343; --gold: #c3a364; --green: #719155; --blue: #556591; --purple: #85577c; /* Font families */ --header-font: 'Montserrat', sans-serif; --body-font: 'Lato', sans-serif; } /* Typography */ h1, h2, h3, h4, h5, h6 { font-family: var(--header-font) !important; font-weight: 600 !important; } .reveal p, .reveal ul, .reveal ol, .reveal li { font-family: var(--body-font) !important; font-size: 0.9em !important; } /* Existing color styles */ h1 { font-size: 1.7em !important; color: var(--orange) !important; } /* orange for main headers */ h2 { font-size: 1.4em !important; color: var(--orange) !important; } /* orange for sub headers */ h3 { font-size: 1.2em !important; color: var(--blue) !important; } /* blue for tertiary headers */ /* Code blocks */ .reveal pre { font-size: 0.75em !important; line-height: 1.1 !important; } .reveal code { font-size: 0.8em !important; } /* List items in code examples */ .reveal pre + ul, .reveal pre + ol { font-size: 0.85em !important; } /* Notes and additional text */ .current, .future { font-size: 0.9em !important; color: var(--green); background: rgba(113, 145, 85, 0.1); padding: 10px; border-radius: 5px; font-family: var(--body-font); } .future { color: var(--purple); background: rgba(133, 87, 124, 0.1); } /* Fragment text */ .reveal .fragment { font-size: 0.9em !important; } .flex-container { display: flex; justify-content: space-between; text-align: left; font-family: var(--body-font); } .flex-item { flex: 1; padding: 0 20px; } .flex-item:not(:first-child) { border-left: 1px solid #ccc; } /* Keep code in monospace */ .reveal pre, .reveal code { font-family: monospace !important; } </style> <!-- markdownlint-disable no-inline-html single-h1 heading-increment --> <!-- .slide: data-background="#ffffff" --> # The `final` Keyword in Java 🔒 ### Understanding Immutability and Constants Note: Today we'll explore the `final` keyword in Java, focusing on its use with variables and the concept of immutability. --- ## What is `final` in Java? 🤔 <div class="fragment fade-up"> The `final` keyword in Java is a non-access modifier that can be applied to: - Variables - Methods - Classes </div> <div class="fragment fade-up"> Today we'll focus on `final` variables: ```java final int MAX_USERS = 100; final String DATABASE_URL = "jdbc:mysql://localhost:3306"; final double PI = 3.14159265359; ``` </div> Note: - Introduce the concept of `final` as a non-access modifier - Show simple examples of `final` variables - Mention that we're focusing on variables today, but `final` has other uses too --- ## `final` Variables: The Basics <div class="fragment fade-up"> <h3>Key Characteristics</h3> - Once assigned, value cannot be changed - Must be initialized (either at declaration or in constructor) - Commonly used for constants (by convention, use UPPER_CASE) - Can be applied to primitives, objects, and references </div> <div class="fragment fade-up"> ```java= // At declaration final int MAX_VALUE = 100; // In constructor private final String id; public Person(String id) { this.id = id; } ``` </div> Note: - Explain the fundamental properties of `final` variables - Show different initialization patterns - Emphasize that `final` means the variable can't be reassigned --- ## Live Example: <br> Transaction Class 🛍️ ```java [5|4|4,10|3|3,9|2|2,8] public class Transaction { private TransactionState currentState; private final List<Product> products; private final LocalDateTime timestamp; private static final double TAX_RATE = 0.06; public Transaction() { this.currentState = TransactionState.IN_PROGRESS; this.products = new ArrayList<>(); this.timestamp = LocalDateTime.now(); } ``` Note: - Walk through the Transaction class example - Point out all three fields are `final` - Note that there are getters but no setters (immutable design) - Highlight initialization in the constructor --- ## Why Use `final` Variables? 🎯 <div class="flex-container"> <div class="flex-item fragment fade-right"> <h3>Immutability</h3> <ul> <li>Prevents accidental changes</li> <li>Thread safety</li> <li>Predictable behavior</li> </ul> </div> <div class="flex-item fragment fade-right"> <h3>Code Quality</h3> <ul> <li>Self-documenting</li> <li>Enforces design intent</li> <li>Compiler optimization</li> </ul> </div> </div> Note: - Discuss the benefits of immutability - Explain how `final` improves code quality - Mention that the compiler can optimize `final` variables --- ## Drawing Memory Model 📝 ### Primitive vs. Non-primitive <div style="display: flex; justify-content: space-around; height: 400px;"> <div style="width: 45%; border: 2px solid #666; text-align: center;"> <h4>Stack</h4> <div style="height: 350px;"> <!-- Stack drawing space --> </div> </div> <div style="width: 45%; border: 2px solid #666; text-align: center;"> <h4>Heap</h4> <div style="height: 350px;"> <!-- Heap drawing space --> </div> </div> </div> --- ## Common Misconception ⚠️ <div class="fragment fade-up"> <h3>`final` Objects vs. Immutable Objects</h3> ```java final ArrayList<String> names = new ArrayList<>(); // This is allowed! The reference is final, not the object content names.add("Alice"); names.add("Bob"); // This is NOT allowed - can't reassign the reference // names = new ArrayList<>(); // Compilation error ``` </div> Note: - Clarify that `final` only makes the reference unchangeable - The object's state can still be modified - True immutability requires more than just `final` --- ## `final` in Practice: Design Patterns 🏗️ <div class="fragment fade-up"> <h3>Immutable Objects Pattern</h3> 1. All fields are `final` 2. Class is `final` (prevents subclassing) 3. No setters 4. Deep copy of mutable fields in constructor 5. Deep defensive copies in getters (if needed) ```java public final class ImmutableProduct { private final String name; private final String sku; private final double price; // Constructor, getters, no setters } ``` </div> Note: - Explain the Immutable Object pattern - Show how `final` is a key part of creating truly immutable objects - Discuss when this pattern is useful (value objects, DTOs, etc.) --- ## `final` in Our Product Class 🔍 <div class="fragment fade-up"> <h3>Benefits in Our Example</h3> - SKU should never change (identity) - Prevents accidental modification - Simplifies reasoning about the code </div> Note: - Analyze why `final` makes sense for the Product class - Connect to real-world concepts (product identity) - Discuss the practical benefits in this specific example --- ## When to Use `final` Variables? 🤔 <div class="flex-container"> <div class="flex-item fragment fade-right"> <h3>Always Consider</h3> <ul> <li>Constants</li> <li>Parameters that shouldn't change</li> <li>Fields representing identity</li> <li>Value objects</li> </ul> </div> <div class="flex-item fragment fade-right"> <h3>Maybe Reconsider</h3> <ul> <li>Variables that need to change</li> <li>When flexibility is needed</li> <li>Temporary/working variables</li> <li>When overcomplicating simple code</li> </ul> </div> </div> Note: - Provide guidelines for when to use `final` - Discuss when it might be overkill - Emphasize that it's a design decision --- ## Best Practices 💡 <div class="fragment fade-up"> 1. Use `final` for all fields that shouldn't change after initialization 2. Consider making parameters `final` to prevent accidental reassignment 3. Use UPPER_CASE for `final` static constants 4. Use camelCase for regular `final` instance variables 5. Combine with proper encapsulation (private fields, getters) 6. If a variable shouldn't be final, then it probably needs some type of setter method. </div> Note: - Share best practices for using `final` - Discuss naming conventions - Emphasize that `final` is part of a larger design approach --- ## Let's Practice! 💻 <div class="fragment fade-up"> Modify this class to use `final` appropriately: ```java public class Customer { private String id; private String name; private int age; private List<Order> orders; public Customer(String id, String name, int age) { this.id = id; this.name = name; this.age = age; this.orders = new ArrayList<>(); } // Getters and setters... } ``` </div> Note: - Guide students through deciding which fields should be `final` - Discuss the implications of these choices - Show the solution after they've had time to think --- ## Solution ✅ ```java public class Customer { private final String id; // ID shouldn't change - it's identity private String name; // Name might change private int age; // Age will change over time private final List<Order> orders; // Reference shouldn't change public Customer(String id, String name, int age) { this.id = id; this.name = name; this.age = age; this.orders = new ArrayList<>(); } // No setter for id, but can still add to orders list public void addOrder(Order order) { this.orders.add(order); } } ``` Note: - Walk through the solution - Explain the reasoning for each decision - Highlight that `orders` is `final` but can still be modified --- <!-- .slide: data-background="#ffffff" --> # Summary <div class="fragment fade-up"> <h3>Key Takeaways</h3> - `final` variables cannot be reassigned after initialization - Use for immutability, thread safety, and code clarity - Remember: `final` reference ≠ immutable object - Consider using `final` for identity fields and constants - Follow naming conventions: UPPER_CASE for static constants, camelCase for instance fields </div> Note: - Summarize the main points about `final` variables - Reinforce the distinction between `final` references and immutable objects - Encourage thoughtful use of `final` in their code --- <!-- .slide: data-background="#ffffff" --> # Questions? 🤔 Note: - Open the floor for questions - Be prepared to discuss edge cases or specific scenarios - Connect the concept to their current projects if possible
{"title":"Week 06: Understanding the `final` Keyword in Java","description":"Exploring the uses and benefits of the `final` keyword in Java","slideOptions":"{\"theme\":\"white\",\"transition\":\"slide\",\"backgroundTransition\":\"fade\"}","contributors":"[{\"id\":\"3c39bbf5-ac66-4d7a-a3c5-1121ba28b46e\",\"add\":23835,\"del\":12680,\"latestUpdatedAt\":null}]"}
    131 views