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