关键字--static

static 可以修饰变量、方法、对象,也可以存在“块”的形式

1、static块

public class StaticDemo {
    static {
        System.out.println("I'm static part!");
    }
    public static String staticVariable = "I'm static variable!";
    public static void main(String[] args) {
        System.out.println(StaticDemo.staticVariable);
    }
}

运行结果:

I'm static part!
I'm static variable!

static块中的代码在类加载时便在执行,且只执行一次。

2、修饰变量

public class StaticDemo {
    static {
        System.out.println("I'm static part!");
    }

    public static String staticVariable = "I'm  static variable!";
    
    public StaticDemo(){
        System.out.println("Here is constructor!");
    }

    public static void main(String[] args) {
        System.out.println(StaticDemo.staticVariable);
        StaticDemo  staticDemo = new StaticDemo ();
    }    

}    

运行结果

I'm static part!
I'm static variable!
Here is constructor!

static变量存放于常量池,不用实例化对象便可进行调用

3、方法

public class StaticDemo {
    static {
        System.out.println("I'm static part!");
    }

    public static String staticVariable = "I'm  static variable!";
    
    public StaticDemo(){
        System.out.println("Here is constructor!");
    }

    static void staticMethod(){
        System.out.println("Here is method");
    }
    public static void main(String[] args) {
        System.out.println(StaticDemo.staticVariable);
        StaticDemo.staticMethod();
        StaticDemo  staticDemo = new StaticDemo ();
    }

}

运行结果

I'm static part!
I'm static variable!
Here is method
Here is constructor!

static方法在内存中只有一份,所有实例对象共享。

面试题:

1、下面程序的结果是什么

public class Test {
    Person person = new Person("Test");
    static{
        System.out.println("test static");
    }
     
    public Test() {
        System.out.println("test constructor");
    }
     
    public static void main(String[] args) {
        new MyClass();
    }
}
 
class Person{
    static{
        System.out.println("person static");
    }
    public Person(String str) {
        System.out.println("person "+str);
    }
}
 
 
class MyClass extends Test {
    Person person = new Person("MyClass");
    static{
        System.out.println("myclass static");
    }
     
    public MyClass() {
        System.out.println("myclass constructor");
    }
}

运行结果为

test static
myclass static
person static
person Test
test constructor
person MyClass
myclass constructor
View Code

首先加载Test类,因此会执行Test类中的static块。接着执行new MyClass(),而MyClass类还没有被加载,因此需要加载MyClass类。在加载MyClass类的时候,发现MyClass类继承自Test类,但是由于Test类已经被加载了,所以只需要加载MyClass类,那么就会执行MyClass类的中的static块。在加载完之后,就通过构造器来生成对象。而在生成对象的时候,必须先初始化父类的成员变量,因此会执行Test中的Person person = new Person(),而Person类还没有被加载过,因此会先加载Person类并执行Person类中的static块,接着执行父类的构造器,完成了父类的初始化,然后就来初始化自身了,因此会接着执行MyClass中的Person person = new Person(),最后执行MyClass的构造器。

执行顺序为:static块->成员变量->构造方法->静态方法

猜你喜欢

转载自www.cnblogs.com/zzyytt/p/9104564.html