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 块 -> 成员变量 -> 构造方法 -> 静态方法
来源: http://www.bubuko.com/infodetail-2622277.html