How to access static properties in an object in Java

1 Answer

0 votes
class Configuration {
    // Define a private static property (shared globally across all instances)
    private static String environment = "production";

    // Public static getter method to access the private static property
    public static String getEnvironment() {
        return environment;
    }

    // Public static setter method to modify the static property safely
    public static void setEnvironment(String newEnv) {
        if (newEnv != null && !newEnv.isBlank()) {
            environment = newEnv;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        // 1. Access static members directly via the Class Name (Best Practice)
        System.out.println("Current Environment: " + Configuration.getEnvironment());

        // 2. Modify the static property via a static setter
        Configuration.setEnvironment("staging");
        System.out.println("Updated Environment: " + Configuration.getEnvironment());

        /* 
         * Note on Public Static Fields:
         * If a static field is declared as 'public', you can access it directly as:
         * 
         * class PublicConfig {
         *     public static String appName = "MyApp";
         * }
         * System.out.println(PublicConfig.appName);
         * 
         * However, public mutable static fields are generally discouraged because 
         * they lack encapsulation and can lead to unintended side effects across threads.
         */
    }
}


/*
run:

Current Environment: production
Updated Environment: staging

*/

 



answered 6 days ago by avibootz
...