关于java:Java-static-关键字总结

7次阅读

共计 1096 个字符,预计需要花费 3 分钟才能阅读完成。

static

当某个事物是动态时,就意味着该 字段 办法 不依赖于任何特定的对象实例。即便咱们从未创立过该类的对象,也能够调用其 静态方法 或拜访其 动态字段 ,这样就不须要 实例化新对象,产生开销。。

相同,对于一般的 非动态字段 办法 ,咱们必须要先创立一个 对象 并应用该对象来拜访 字段 办法 ,因为 非动态字段和办法 必须与 特定对象 关联。

static 变量和办法

class Util {
    public final int num = 100;

    public static int staticNum = 100;

    public int getAbs(int num) {return Math.abs(num);
    }

    public static int getSum(int a, int b) {
        // 谬误,不能静态方法不能拜访非动态变量。System.out.println(c);
        
        // 谬误,不能静态方法不能拜访非动态变量。getAbs(-10);
        return a + b;
    }
}

class Main {public static void main(String[] args) {
        // 正确,通过类拜访静态方法
        System.out.println(Util.getSum(1, 2));

        // 正确,通过类拜访动态变量
        System.out.println(Util.staticNum);

        // 正告,通过类的实例调用静态方法,相当于 Util.getSum(1, 2)。// 此处尽管不会保留,但可能会产生一系列问题,不举荐应用、System.out.println(new Util().getSum(1, 2));
    }
}

当应用 static 润饰的某个 办法 | 变量 时候,咱们称其为 静态方法 | 变量

静态方法 | 变量 不属于任何 对象 ,因而不能够通过this 关键字调用该 办法 | 变量 ,只能够通过 类名 来拜访。

静态方法中 不能拜访该类的 非动态成员变量 非动态成员办法 ,因为类的 非动态成员变量 非动态成员办法 都必须依赖 具体的对象 才可能被调用。

static 代码块

class Test {
    static {System.out.println("static block!");
    }

    public Test() {System.out.println("constructor!");
    }
}

public class Main {public static void main(String[] args) {
        /**
         * 运行后果
         * static block!* constructor!* constructor!*/
        new Test();
        new Test();}
}

动态代码块 只会在 类加载 的时候只会 执行一次 ,接下的 类加载 都不会执行。因而 初始化操作 能够放到 动态代码块 中执行,能够大大晋升效率。

正文完
 0