Built with Tutify.io

    AIStudyLabs

    Final and Static Keywords Explained

    Final and Static Keywords Explained

    Introduction

    In this lesson, we will explore the final and static keywords in Java, essential components of the language's object-oriented programming (OOP) architecture. You will understand how these keywords modify the behavior of classes, methods, and variables, and when it's appropriate to use them in your coding practices. Additionally, we will delve into practical coding examples to illustrate their functionalities in real-world applications.

    The Purpose of the Final Keyword in Java

    The final keyword in Java is used to restrict the user from modifying a variable, method, or class. Once declared as final, the following rules apply:

    Final Variables

    A final variable is a constant that holds a value which cannot be changed once assigned. Here’s an example:

    public class FinalExample {
        final int CONSTANT_VALUE = 100;
    
        public void tryToChangeValue() {
            // Uncommenting the line below will cause a compilation error
            // CONSTANT_VALUE = 200; 
        }
    }
    

    Output:

    // Compilation Error: cannot assign a value to final variable CONSTANT_VALUE
    

    Final Methods

    When a method is declared as final, you prevent any subclasses from overriding it, preserving its original implementation. For example:

    class Parent {
        final void display() {
            System.out.println("This is a final method.");
        }
    }
    
    class Child extends Parent {
        // This will cause a compilation error if uncommented
        // void display() {
        //     System.out.println("Overriding final method");
        // }
    }
    

    Output:

    // Compilation Error: cannot override display() in Child
    

    Final Classes

    A final class cannot be subclassed, making it immutable in terms of its structure. Here's an example:

    final class FinalClass {
        void show() {
            System.out.println("Cannot inherit this class.");
        }
    }
    
    // Uncommenting the line below will cause a compilation error
    // class ExtendedClass extends FinalClass {}
    

    The Static Keyword for Class-Level Members

    The static keyword in Java denotes that the particular member belongs to the class itself rather than any instance of the class. It can be applied to variables, methods, and blocks.

    Static Variables

    Static variables are shared among all instances of a class, as they belong to the class itself. Here's an example:

    class Counter {
        static int count = 0;
    
        Counter() {
            count++;
            System.out.println("Count: " + count);
        }
    }
    
    public class TestStatic {
        public static void main(String[] args) {
            new Counter();
            new Counter();
            new Counter();
        }
    }
    }
    

    Output:

    Count: 1
    Count: 2
    Count: 3
    

    Static Methods

    Static methods can be called without creating an instance of the class and can only access static variables and methods. Seen below:

    class StaticDemo {
        static void staticMethod() {
            System.out.println("Static method called.");
        }
    }
    
    public class TestStaticMethod {
        public static void main(String[] args) {
            StaticDemo.staticMethod(); // Call without instance
        }
    }
    

    Output:

    Static method called.
    

    Using Final and Static Together

    Combining both keywords can be useful. A static final variable typically represents a constant value that remains unchanged across instances and belongs to the class itself. Here’s an example:

    class Constants {
        static final double PI = 3.14159;
    }
    
    public class TestConstants {
        public static void main(String[] args) {
            System.out.println("Value of PI: " + Constants.PI);
        }
    }
    

    Output:

    Value of PI: 3.14159
    

    Practical Coding Example: Creating a Static Final Class

    Let’s illustrate the use of static final by creating a utility class that contains constants and static methods:

    class MathUtils {
        static final double SQUAREROOT_2 = 1.414;
    
        static double square(double number) {
            return number * number;
        }
    }
    
    public class TestMathUtils {
        public static void main(String[] args) {
            System.out.println("Square of 4: " + MathUtils.square(4));
            System.out.println("Square root of 2: " + MathUtils.SQUAREROOT_2);
        }
    }
    

    Output:

    Square of 4: 16.0
    Square root of 2: 1.414
    

    Summary / Key Takeaways

    In this lesson on Final and Static Keywords Explained, you have learned:

    Java Fundamentals For Beginners — Object-Oriented Programming (OOP) Concepts

    Introduction to Java

    Java Basics

    Java Basic Programs

    Understanding Java Classes and Methods

    Working with Strings

    Object-Oriented Programming (OOP) Concepts

    Exception & Error Handling

    File Handling (I/O Operations)

    Java Packages and Libraries

    Best Practices in Java Programming

    Building Simple Console-Based Applications

    Moving Forward: Advanced Topics

    Course Review and Final Project

    Tutorial Not Found