代码块问题现详解

在Java中使用,{}包起来的内容,称为代码块
代码块分为:
局部代码块
在类中的局部位置(方法中定义)
作用:限定当前该局部变量的生命周期,仅仅是在当前代码块作用域中有效
构造代码块
在类中的成员位置使用{}定义,每次执行构造方法之前,先执行构造代码块如果有构造代码块
作用:可以将多个构造方法中的相同的代码可以放到构造代码块中,给对象进行初始化!
静态代码块
在类中的成员位置,static{} ,特点每次只执行一次,优先于对象存在
作用:给类进行初始化的
注意:
静态代码块只加载一次!
优先级:
静态代码块> 构造代码块>构造方法代码块

class Code{		//code.class只加载一次
//静态代码块
	static{
		int x = 1000 ;
		System.out.println(x) ;  //1000
	}
	//构造代码块
	{
		int x = 100 ; 
		System.out.println(x) ;//100
	}
	//无参构造方法
	public Code(){
		System.out.println("code...") ;
	}
		//有参构造方法
	public Code(String name){
		System.out.println(name); 
	}
	//构造代码块
	{
		int y = 200 ;
		System.out.println(y) ; //200
	}
	
//静态代码块
	static{
		int y = 2000 ;
		System.out.println(y) ; 
	}
	
}

//测试类
class CodeTest{
	public static void main(String[] args){
		//局部代码块
		{
			int x  = 10 ;
			System.out.println(x) ;//10
		}
		{
			int y  = 20 ;
			System.out.println(y) ;//20
		}
			//创建Code类对象
		Code code = new Code();	
		Code code2 = new Code("高圆圆");
	}
}

输出结果:
10
20
1000
2000
100
200
100
200
高圆圆

看程序,写结果:
静态代码块的特点:随着的类的加载而加载(只执行一次)
以及静态代码块,构造代码块,构造方法的优先级

class Student{
	static {
		System.out.println("Student的静态代码块") ;
	}
	public Student(){
		System.out.println("Student的构造方法") ;
	}
	{
		System.out.println("Student构造代码块");
	}
}
//测试类
class StudentTest{
	static{
		System.out.println("高圆圆已经40了,我很伤心...") ;
	}
	public static void main(String[] args){
		System.out.println("main") ;
		Student s = new Student();
		Student s2 = new Student() ;
	}
}		
	

输出结果:
高圆圆已经40了,我很伤心…
main
Student的静态代码块
Student构造代码块
Student的构造方法
Student构造代码块
Student的构造方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值