面向对象(代码块)

代码块:

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

根据其位置和声明的不同,可以分为:

A:局部代码块:局部位置,用于限定变量的生命周期。

class CodeDemo {
    public static void main(String[] args) {
        //局部代码块
        {
            int x = 10;
            System.out.println(x);
        }

  }

}

构造代码块:

在类中的成员位置,用{}括起来的代码。每次调用构造方法执行前,都会先执行构造代码块。

 作用:可以把多个构造方法中的共同代码放到一起,对对象进行初始化。 

class Code {
    //静态代码块
	static {
		int a = 1000;
		System.out.println(a);
	}

	//构造代码块----成员变量的位置
	{
		int x = 100;
		System.out.println(x);
	}
	
	//构造方法
	public Code(){
		System.out.println("code");
	}

静态代码块:

在类中的成员位置,用{}括起来的代码,只不过它用static修饰了。
作用:一般是对类进行初始化。

class Code {
	static {
		int a = 1000;
		System.out.println(a);
	}

	//构造代码块
	{
		int x = 100;
		System.out.println(x);
	}
	
	//构造方法
	public Code(){
		System.out.println("code");
	}
	
	//构造方法
	public Code(int a){
		System.out.println("code");
	}
	
	//构造代码块
	{
		int y = 200;
		System.out.println(y);
	}
	
	//静态代码块
	static {
		int b = 2000;
		System.out.println(b);
	}
}

面试题?
        静态代码块,构造代码块,构造方法的执行顺序?
        静态代码块 -- 构造代码块 -- 构造方法
--------不管位置在哪里程序执行的顺序不变,静态代码块优先输出。
        静态代码块:只执行一次------------------整个main方法中只输出一次
        构造代码块:每次调用构造方法都执行 

案例分析

class Code {
	static {
		int a = 1000;
		System.out.println(a);
	}

	//构造代码块
	{
		int x = 100;
		System.out.println(x);
	}
	
	//构造方法
	public Code(){
		System.out.println("code");
	}
	
	//构造方法
	public Code(int a){
		System.out.println("code");
	}
	
	//构造代码块
	{
		int y = 200;
		System.out.println(y);
	}
	
	//静态代码块
	static {
		int b = 2000;
		System.out.println(b);
	}
}

class CodeDemo {
	public static void main(String[] args) {
		//局部代码块
		{
			int x = 10;
			System.out.println(x);
		}
		//找不到符号
		//System.out.println(x);
		{
			int y = 20;
			System.out.println(y);
		}
		System.out.println("---------------");
		
		Code c = new Code();	
		System.out.println("---------------");
		Code c2 = new Code();
		System.out.println("---------------");
		Code c3 = new Code(1);
	}
}

上述程序的运行结果如下:

10
20
---------------
1000--静态代码块
2000---静态
100---构造代码块
200---构造代码块
code---构造方法
---------------
100----构造代码块
200----构造代码块
code---构造方法
---------------
100----构造代码块
200----构造代码块
code----构造方法

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值