Java中static关键字的作用

在Java中,static关键字用于内存管理,分享相同的变量或者方法。

基本上,static修饰常量或者在类的每个实例中都相同的方法,main方法通常都用static修饰。

当类中的一个成员变量或者成员方法被声明为static,那么可以在对象创建之前访问该成员变量或方法,而不需要对象引用。

static主要用于以下几种情况:

  • static block
  • static variable
  • static methods
  • static classes

static block

初始化静态变量的代码可以放在static block里面,这样在类加载之后,里面的代码就会先执行。

// Java program to demonstrate the use of static blocks
import java.util.*;
public class BlockExample{
	// static variable
	static int j = 10;
	static int n;

	// static block
	static {
	System.out.println("Static block initialized.");
	n = j * 8;
	}
	public static void main(String[] args){
		System.out.println("Inside main method");
		System.out.println("Value of j : "+j);
		System.out.println("Value of n : "+n);
	}
}

static variable

// Java program demonstrate execution of static blocks and variables

import java.util.*;

public class VariableExample {
    // static variable
    static int j = n();

    // static block
    static {
        System.out.println("Inside the static block");
    }

    // static method
    static int n() {
        System.out.println("from n ");
        return 20;
    }

    // static method(main !!)
    public static void main(String[] args) {
        System.out.println("Value of j : " + j);
        System.out.println("Inside main method");
    }
}

static methods

被static修饰的方法有两个限制:

  • 只能直接调用其它静态方法
  • 只能直接访问静态数据
// java program to demonstrate restriction on static methods
public class StaticMethodExample {
    // static variable
    static int j = 100;

    // instance variable
    int n = 200;

    // static method
    static void a() {
        a = 200;
        System.out.println("Print from a");

        // Cannot make a static reference to the non-static field b
        n = 100; // compilation error

        // Cannot make a static reference to the
        // non-static method a2() from the type Test
        a2(); // compilation error

        // Cannot use super in a static context
        System.out.println(super.j); // compiler error
    }

    // instance method
    void a2() {
        System.out.println("Inside a2");
    }

    public static void main(String[] args) {
        // main method
    }
}

static classes

只有当一个类被嵌套使用的时候才能被static修饰

public class NestedExample {
    private static String str = "Edureka";
    // Static class
    static class MyNestedClass {
        // non-static method
        public void disp() {
            System.out.println(str);
        }
    }
    public static void main(String args[]){
    NestedExample.MyNestedClass obj = new NestedExample.MyNestedClass();
    obj.disp();
     
    }
}

参考链接:[https://www.edureka.co/blog/static-keyword-in-java/#::text=In%20Java%2C%20static%20keyword%20is,every%20instance%20of%20a%20class.](https://www.edureka.co/blog/static-keyword-in-java/#::text=In Java%2C static keyword is,every instance of a class.)

原文地址:https://www.cnblogs.com/realzhaijiayu/p/13456697.html