PROGRAMMING

MINTE9
REMEMBERS




Last update:   23-07-2021

Static Variables

p279 Static variables are initialized only once. A static class variable is common to all objects created with that class.
 RunCode
class LearningApp {
    public static void main(String[] args) {
        Dog d1 = new Dog();
        Dog d2 = new Dog();
        System.out.println(d2.getCount()); // 2
    }
}

class Dog {

    private static int dogCount = 0; // static variable
    
    public Dog() {
        dogCount++;
    }
    public int getCount() {
        return dogCount; // OR this.dogCount
    }
}
... 10 lines
˄˄˄
A static variable can be called without object instantiation.
 RunCode
class LearningApp {
    public static void main(String[] args) {

        System.out.println(Animal.name); // Weirdo
    }
}
class Animal {
    public static String name = "Weirdo";
}
... 2 lines
˄˄˄
Static Methods    (2/4)

Static methods

p275 ! Static methods belong to the class and not every instance of the class Java.lang.Math has a round() static method.
 RunCode
class LearningApp {

    public static void main(String[] args) {

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

        //Math m = new Math(); // Error: private access
    }
}
... 1 lines
˄˄˄

Import static

With static import we can access a static member of a class without class name. It improves code readability but might lead to confusion, use it with care.
 RunCode

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

class LearningApp {

    public static void main(String[] args) {

        System.out.println(round(42.2)); // Look Here

        // Math.round(42.2));
    }
}
... 1 lines
˄˄˄
Static Class    (3/4)

Static class

Only nested classes can be static. You can use the nested class without an instance for outer class.
 RunCode
class App {

    public static void main(String[] args) {
        
        A.B.run(); // 10
    }

    static class A {

        static int a = 10;
    
        static class B {

            public static void run() {
                
                System.out.println(a); // field from Outer Class
            }
        }
    }
    
}
... 7 lines
˄˄˄
Task

 CompleteTask
/** 
Define MyMath.floor() method using java.lang.math method

class LearningApp {
    public static void main(String[] args) {
        double n = MyMath.floor(12.3);
        System.out.print(n); // 12.0
    }
}
*/

// SOLUTION

???

solution code
Questions    
12. Abstract
11 . Static
Last update:   23-07-2021

        A B C D E F
🔔
1/2