代码块的概述和分类

1.代码块概述

在Java中,使用{ }括起来的代码称为代码块

2.代码块分类

根据其位置和声明不同,可以分为局部代码块,构造代码块,静态代码块,同步代码块

3.常见代码块的应用

  • 局部代码块

在方法中出现;限定变量的声明周期,及早释放,提高内存利用率

  • 构造代码块(初始化块)

在类中方法外出现;多个构造函数方法中相同代码存放到一起,每次调用构造都执行,并且在构造方法前执行

public class Car {
	
	private String color;	//颜色
	private int num;		//轮胎数
	
	public Car() {
		System.out.println("空参构造");
	}
	public Car(String color, int num) {
		super();
		this.color = color;
		this.num = num;
		System.out.println("有参构造");
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	
	{
		System.out.println("构造代码块");
	}
	
	
	public static void main(String[] args) {
		
		Car c1 = new Car();
		System.out.println("=================");
		Car c2 = new Car("绿色", 4);
	}
}

  • 静态代码块

在类中方法外出现,加了static修饰

在类中方法外出现,并加上了static修饰;用于给类进行初始化,在加载的时候就执行,并且只执行一次

一般用于加载驱动,优先于主方法main执行

public class Car {
	
	private String color;	//颜色
	private int num;		//轮胎数
	
	public Car() {
		//run();
		System.out.println("空参构造");
	}
	public Car(String color, int num) {
		//run();
		this.color = color;
		this.num = num;
		System.out.println("有参构造");
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	
	{
		run();
	}
	
	public void run(){
		System.out.println("车在运行");
	}
	
	static {
		System.out.println("静态代码块.....");
	}
	
	public static void main(String[] args) {
		
		Car c1 = new Car();
		System.out.println("=================");
		Car c2 = new Car("绿色", 4);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值