1、修饰成员 不属于对象,在加载类的时候 已经为静态成员分配好内存栈中,可以通过KeyWord.name来访问
class KeyWord {
public static String name = "HelloWorld";
}
public class StaticKeyWord {
public static void main(String[] args) {
System.out.println(KeyWord.name);
}
}
2、修饰方法 访问 KeyWord.sayHello()
class KeyWord {
public static String name = "HelloWorld";
public static void sayHello(){
System.out.println(name);
}
}
public class StaticKeyWord {
public static void main(String[] args) {
System.out.println(KeyWord.name);
KeyWord.sayHello();
}
}
3、修饰类,比如静态内部类
静态内部类是属于外部类,而不属于外部类的对象
创建静态内部类的时候是不需要将静态内部类的实例对象绑定到外部类的实例对象上。
可以访问外部的静态成员和和静态方法
实例化 StaticKeyWord.Hello hello = new StaticKeyWord.Hello hello();
class KeyWord {
public static String name = "HelloWorld";
public static void sayHello(){
System.out.println(name);
}
//静态内部类对象生成
public static void staticClassConstructor(){
StaticKeyWord.Hello hello = new StaticKeyWord.Hello();
}
//普通内部类对象生成生成
public static void noStaticClassContructor(){
StaticKeyWord staticKeyWord = new StaticKeyWord();
StaticKeyWord.NoStaticClassHello noStaticClassHello =
staticKeyWord.new NoStaticClassHello();
}
}
public class StaticKeyWord {
private static String key = "static";
public static void main(String[] args) {
System.out.println(KeyWord.name);
KeyWord.sayHello();
System.out.println(new Hello().getKey());
}
//静态内部类 属于类
static class Hello{
public String getKey(){
return key;
}
}
//内部类 属于对象
class NoStaticClassHello{
public String getKey(){
return key;
}
}
}
4 修饰静态代码块 在类加载的时候会执行静态块的代码
public class StaticBlock {
static {
System.out.println("===============");
}
public static void main(String[] args) {
System.out.println("HelloWorld StaticBlock");
}
}
//执行结果
===============
HelloWorld StaticBlock
5 修饰包导入 导入其它类的静态成员
import static java.lang.String.CASE_INSENSITIVE_ORDER;