minte9
LearnRemember



Variables

Static variables are initialized only once.
 
/**
 * Static variables are initialized only once.
 * 
 * A static class variable is common to all objects created with that class. 
 * It can be called without object instantiation.
 */

package com.minte9.oop.static_keyword;

public class Variables {
    public static void main(String[] args) {

        A a1 = new A();
        A a2 = new A();
        
        System.out.println(a1.getCount()); // 2 (not 1)
        System.out.println(a2.getCount()); // 2
    }
}

class A {

    private static int count;

    public A() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

Methods

Static methods can't be access from a class instances.
 
/**
 * Static methods belong to the class and not every instance of the class.
 * Example: Java.lang.Math has a round() static method.
 */

package com.minte9.oop.static_keyword;

public class Methods {
    public static void main(String[] args) {

        System.out.println(
            Math.round(42.2) // 42
        );

        System.out.println(
            Methods.myRound(33.5) // 34
        );

        // Math m = new Math(); // Error: private access
    }

    private static long myRound(Double n) {
        return Math.round(n);
    }
}

Classes

Only nested classes can be static.
 
/**
 * Static classes
 * 
 * Only nested classes can be static
 * You can use the nested class without an instance for outer class
 */

package com.minte9.oop.static_keyword;
public class Classes {

    static int a = 10;
    public static void main(String[] args) {
        InnerClass.run(); // 10
    }
    
    static class InnerClass {
        public static void run() {
            System.out.println(a); // field from Outer Class
        }
    }
}



  Last update: 432 days ago