Thinking in java-14 static 关键字

来源:互联网 发布:男人中式服装品牌知乎 编辑:程序博客网 时间:2024/05/21 10:58

1.static关键字意义

这里有关于static的Q&A.

package com.fqyuan.test;public class TestStatic{    //If add static here, codes below will work fine.    Clock clock = new Clock();    public static void main(String[] args){        clock.sayTime();//Error here, can't accesss non-static field in static method main    }}

这里写图片描述

  • static 成员是属于类的,而不是属于某个特定的对象实例。
  • 只有一个静态域的实例存在,无论我们创建无论多少个成员实例,甚至一个对象实例也不创建。静态域会被所有的实例所共享。
  • 静态方法不属于任何特定的对象实例,所以它们不能访问任何实例成员(因为你并不知道你所要访问的实例成员属于哪一个实例对象)。所以静态方法只能访问静态成员不能访问非静态成员,而实例方法则没有此限制。
public class Example{    private static boolean staticField;    private boolean instanceField;    public static void main(String[] args){    //A static method can access static fields    staticField = true;    //A static method can access instance fields through an object reference    Example example = new Example();    example.instanceField = true;    }}

2. static的使用情况

You don’t actually get an object until you create one using new, and at that point storage is allocated and methods become available.
Two situations this approach is not sufficient.
One is if you want to have only a single piece of storage for a particular field, regardless of how many objects of that class are created, or even if no objects are created.
The other is if you need a method that isn’t associated with any particular object of this class. That is, you need a method that you can call even if on objects are created.
Tips: Since static don’t need any objects to be created before they are used, they cannot directly access non-static members or methods by simply calling those other members without referring to a named object (Since non-static members and methods must be tied to a particular object.)

在我们使用 new 操作符创建对象时,我们才真正得到一个对象实例,此时对象内存被分配,类方法可以被调用了。
但是2种情况下这种情况并不适用。

  1. 当我们对于某个特定的域无论创建多少个个体甚至一个个体都不创建,只想要该数据域的一片实例时该怎么办呢?
  2. 当我们需要的方法不和特定类的实例对象相关联时,即:我们不需要创建对象即可调用方法,那我们应该怎么做呢?

解决方案:使用static关键字修饰类的成员变量和成员方法即可。

原创粉丝点击