day08-静态代码块
This commit is contained in:
30
day08/src/com/inmind/static02/Demo10.java
Normal file
30
day08/src/com/inmind/static02/Demo10.java
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
package com.inmind.static02;
|
||||||
|
/*
|
||||||
|
静态代码块:
|
||||||
|
定义在成员位置,使用static修饰的代码块{ }。
|
||||||
|
位置:类中方法外。
|
||||||
|
执行:随着类的加载而执行且执行一次,优先于main方法和构造方法的执行。
|
||||||
|
|
||||||
|
格式:
|
||||||
|
static{
|
||||||
|
java语句;
|
||||||
|
}
|
||||||
|
|
||||||
|
静态代码块的作用:在程序运行之前,就进行一些操作,常用于对静态变量的初始化操作,后期工作中常用于对配置文件的值赋值操作
|
||||||
|
*/
|
||||||
|
public class Demo10 {
|
||||||
|
static int i = 10;
|
||||||
|
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
System.out.println("main方法");
|
||||||
|
Student s = new Student();
|
||||||
|
System.out.println("程序结束");
|
||||||
|
}
|
||||||
|
|
||||||
|
//静态代码块
|
||||||
|
static{
|
||||||
|
i = 20;
|
||||||
|
System.out.println("静态代码块执行了");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ public class Student {
|
|||||||
//静态变量
|
//静态变量
|
||||||
static String clazz;
|
static String clazz;
|
||||||
public Student() {
|
public Student() {
|
||||||
|
System.out.println("Student无参构造被调用");
|
||||||
}
|
}
|
||||||
public Student(String name, int age) {
|
public Student(String name, int age) {
|
||||||
this.name = name;
|
this.name = name;
|
||||||
|
|||||||
Reference in New Issue
Block a user