PROGRAMMING

 
REMEMBERS




Static Variables

p279 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
        System.out.println(a2.getCount()); // 2

        System.out.println(A.id); // 100
    }
}

class A {

    private static int count = 0;
    public static int id = 100;

    public A() {
        count++;
    }
    public int getCount() {
        return count;
    }
}

... 20 lines
 

Static methods

p275 ! 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);
    }
}
... 14 lines
 

Static classes

Only nested classes can be static.
 
/**
 * 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
        }
    }
}
... 11 lines
 

Import static

With static import we can access a static member of a class without class name.
 
/**
 * Static import improves code readability but might lead to confusion, ...
 * use it with care.
 * 
 * Effective Java: "Use static imports ...
 * if you find yourself heavily using constants from a utility class"
 */

package com.minte9.oop.static_keyword;

import static java.lang.Math.round; // Look Here

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

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

... 11 lines
 

Questions     github OOP
Abstract Keyword

        A B C D E F
🔔
1/2