zoukankan      html  css  js  c++  java
  • 03-14_代码块

    代码块

    在程序编写之中可以直接使用“{}”定义一段语句,那么根据此部分定义的位置以及声明的关键字的不同,代码块一共可以分为四种:

    • 普通代码块
    • 构造块
    • 静态块
    • 同步代码块(多线程时讲解)。

    范例:编写普通代码块

    public class TestDemo {
    	public static void main(String args[]) {
    		{ 	// 普通代码块
    			int num = 10; 		// 局部变量
    			System.out.println("num = " + num);
    		}
    		int num = 100; 		// 全局变量
    		System.out.println("num = " + num);
    	}
    }
    程序执行结果:
    num = 10
    num = 100
    
    

    范例:定义构造块

    class Book {
    	public Book() { 		// 构造方法
    		System.out.println("【A】Book类的构造方法");
    	}
    	{ 	// 将代码块写在了类里面,所以为构造块
    		System.out.println("【B】Book类中的构造块");
    	}
    }
    public class TestDemo {
    	public static void main(String args[]) {
    		new Book();		// 实例化类对象
    		new Book();		// 实例化类对象
    	}
    }
    程序执行结果:
    【B】Book类中的构造块
    【A】Book类的构造方法
    【B】Book类中的构造块
    【A】Book类的构造方法
    
    

    情况一:在非主类中使用静态块

    class Book {
    	public Book() { 					// 构造方法
    		System.out.println("【A】Book类的构造方法");
    	}
    	{	// 将代码块写在了类里面,所以为构造块
    		System.out.println("【B】Book类中的构造块");
    	}
    	static {			// 定义静态块
    		System.out.println("【C】Book类中的静态块") ;
    	}
    }
    public class TestDemo {
    	public static void main(String args[]) {
    		new Book();		// 实例化类对象
    		new Book();		// 实例化类对象
    	}
    }
    程序执行结果:
    【C】Book类中的静态块
    【B】Book类中的构造块
    【A】Book类的构造方法
    【B】Book类中的构造块
    【A】Book类的构造方法
    
    

    情况二:在主类中定义静态块

    public class TestDemo {
    	public static void main(String args[]) {
    		System.out.println("Hello World !");
    	}
    	static { 			// 静态块
    		System.out.println("更多资源请访问:www.yootk.com");
    	}
    }
    
    程序执行结果:
    更多资源请访问:www.yootk.com
    Hello World !
    
    
    
    
  • 相关阅读:
    第一节:SpringMVC概述
    SpringMVC【目录】
    Windows 系统快速查看文件MD5
    (error) ERR wrong number of arguments for 'hmset' command
    hive使用遇到的问题 cannot recognize input
    Overleaf支持的部分中文字体预览
    Understanding and Improving Fast Adversarial Training
    Django2实战示例 第十三章 上线
    Django2实战示例 第十二章 创建API
    Django2实战示例 第十一章 渲染和缓存课程内容
  • 原文地址:https://www.cnblogs.com/xuwei1/p/8406186.html
Copyright © 2011-2022 走看看