class Chinese {
//身份证号【每个对象的身份证号不同】
//实例变量
int id;
//姓名【每一个对象的姓名不同】
//实例变量
String name;
//实例对象存储在java对象内部,在堆内存当中,在构造方法执行的时候初始化
//国籍【所有对象国籍一样,这种特征属于类级别的特征,可以提升为整个模板的特征,可以在变量前添加static关键字修饰】
//静态变量,静态变量在类加载的时候初始化,不需要创建对象,内存就开辟了
//所有的中国人的国籍都是"中国",这里声明为实例变量显然是不太合适的,太浪费内存空间,没不要让每个对象都保存一份“国籍”内存
static String country = "中国";
public Chinese(){
/*this.id = 0;
this.name = null;
this.country = null;*/
}
public Chinese(int id,String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static String getCountry() {
return country;
}
public static void setCountry(String country) {
Chinese.country = country;
}
}
public class ChineseTest {
public static void main(String[] args) {
//创建Chinese对象1
Chinese c1 = new Chinese(1,"zahgnsan");
System.out.println(c1.id + " " + c1.name + " " + Chinese.country);
//创建Chinese对象2
Chinese c2 = new Chinese(2,"lisi");
System.out.println(c2.id + " " + c2.name + " " + Chinese.country);
//创建Chinese对象3
Chinese c3 = new Chinese(3,"wangwu");
System.out.println(c3.id + " " + c3.name + " " + Chinese.country);
System.out.println(c1.country);
c1 = null;
//所有静态的数据都输可以采用类名.,也可以采用引用,但是建议采用类名.的方式访问。
//采用引用.的方式的时候,即使引用是null,也不会出现空指针异常。因为访问静态变量的数据不需要对象的存在
System.out.println(c1.country);
}
}
static{
java语句;
}
2.静态代码块在类加载是执行,并且只执行一次
3.静态代码块在一个类中可以编写多个,并且遵循自上而下的循序依次执行。
4.静态代码块的作用是什么?用在呢?什么时候用?
这当然和具体的需求有关,例如项目中要求在类加载的时刻/时机执行代码完成日志的记录,那么这段记录日志的代码就可以编写到静态代码块当中,完成日志记录,静态代码块是java程序员准备一个特殊的时刻,这个特殊的时刻被称为类加载时刻。若希望在此刻执行一段特殊的程序,这段程序可以直接放到静态代码块中。
5.通常在静态代码块当中完成预备工作,先完成数据的准备工作,例如:初始化连接池,解析XML配置文件…
public class StaticTest01 {
static{
System.out.println("类加载1 -->");
}
static{
System.out.println("类加载2 -->");
}
static{
System.out.println("类加载3 -->");
}
public static void main(String[] args) {
System.out.println("main -->");
}
}
静态方法中无法直接访问实例变量和实例方法
class MathUtil {
public static int sumInt(int a,int b){
return a + b;
}
public static int divide(int a,int b){
return a / b;
}
}
public class StaticTest03 {
//实例变量
int i = 10;
//实例方法
public void doSome(){
}
//静态主方法
public static void main(String[] args) {
StaticTest03 st = new StaticTest03();
System.out.println(st.i);
st.doSome();
//使用数学工具类
System.out.println(MathUtil.sumInt(20,30));
System.out.println(MathUtil.divide(20,30));
}
}
/*
* 总结:
* class{
* 静态代码块;
* 实例代码块;
*
* 静态变量;
* 实例变量;
*
* 构造方法;
*
* 静态方法;
* 实例方法;
* }
*
*
*
*
*
* */
public class StaticTest2 {
//构造函数
public StaticTest2(){
System.out.println("缺省构造器执行!");
}
//实例代码块
{
System.out.println(1);
}
//实例代码块
{
System.out.println(2);
}
//实例代码块
{
System.out.println(3);
}
public static void main(String[] args) {
System.out.println("main begin!");
new StaticTest2();
new StaticTest2();
}
}