• Notice: Static


    只有非 private (public, protected, or no identifier) 的 static 成员 (成员指属性和方法)才能通过类名的方式访问。 static 只是表明该成员具有了可以通过类名访问的潜在特征,但是否可以通过类名访问 (class.xxx),还必须具备一个条件:该成员必须是非private
    Sample:
    ====================
    package ch.allenstudy.newway01;

    public class Recursion1
    {
    public static void main(String[] args)
    {
    System.out.printf(“Now print public AA.i: %d\n”, AA.i);
    System.out.printf(“Now print public AA.j: %d\n”, AA.j);
    System.out.printf(“Now print default AA.k: %d\n”, AA.k);
    }
    }
    class AA
    {
    public static int i = 10;
    protected static int j = 11;
    static int k = 12;
    }
    ———–Result————
    Now print public AA.i: 10
    Now print public AA.j: 11
    Now print default AA.k: 12
    ======================================
    可以从非静态方法中访问静态成员(属性和方法),但不能从静态方法中访问非静态成员(属性和方法)。
    package ch.allenstudy.newway01;
    public class Recursion1
    {
    public static void main(String[] args)
    {
    AA aa = new AA();
    aa.callShow(); //call the dynamic method callShow();
    }
    }
    class AA
    {
    public static int i = 10; //i is a static property
    public static void show() //show() is a static method
    {
    System.out.printf(“i= %d”, i);
    }
    public void callShow()
    {
    show(); //Call the static method show()
    }
    }
    From up sample you can see that we can call a static method show() from the dynamic method callShow().
    Overall,please remember: 类的静态成员(方法和属性)是类天生就有的。我们可以这样想,比如我们说汽车类,汽车类都有名字这个 属性和驾驶这个方法。所以当你new出来任何一个具体的汽车对象(whatever 宝马还是大众),他们肯定有个名字,也肯定能够驾驶。
    这就说明类的非私有静态成员可以被以 class.成员 的方式直接访问。
    同时,类的静态成员由所有的对象所公用。所以一旦一个实例化出来的对象更改了静态属性的值,另一个对象再使用这个静态属性时,使用的就是新的值。本质上来说,静态成员被放置在内存的 data segment 中,而且只有一份,只要改了,就改了。

  • 相关阅读:
    memcache 应用场景
    如何写接口文档(登录)
    PHP常见错误级别及错误码
    ex33 while 循环
    ex32 循环和列表
    ex31--作出决定
    ex29-30 if,elif and else.
    ex28 布尔表达式练习
    ex25 更多更多的实践
    ex21 函数可以返回某些东西
  • 原文地址:https://www.cnblogs.com/backpacker/p/2271549.html
Copyright © 2020-2023  润新知