JAVA中代码块
2017-08-24 10:14
106 查看
1 普通代码块
为了防止在方法里面编写的代码的变量重名,对一个方法进入一个局部的分割,但是基本上没有什么意义。因为一个方法的代码不会写得很长,同时我们在对变量的命名的时候都是有意义的定义。
定义如下:
2 构造块
将一个代码块写在一个类里面
运行方法:
Book类:
运行结果:
我们发现构造块先运行,产生多个对象,构造块会出现多次。
3 静态块
如果代码块使用了static进行定义的话,那么就称它为静态块,有两种使用的情况
情况1: 在非主类中使用:
运行方法:
Book类
运行结果:
从运行结果,我们可以看出,静态块的优先级高于构造块与构造方法。静态块一般是给静态属性初始化,但是使用比较少。
情况二:在主类中定义
运行结果:
静态块优先于主方法执行。在JDK1.7之前,可以没有主方法也能运行,只要有一个静态块也能运行,但是在1.7之后,这个BUG已经修复。
4总结
代码块能不用就不用,在编写测试可以使用静态块来做一些数据的初始化。
为了防止在方法里面编写的代码的变量重名,对一个方法进入一个局部的分割,但是基本上没有什么意义。因为一个方法的代码不会写得很长,同时我们在对变量的命名的时候都是有意义的定义。
定义如下:
public static void main(String[] args) { { // 普通代码块 int num = 10 ; //局部变量 System.out.println("num = " + num); // 10 } int num = 100 ; //全局 System.out.println("num = " + num); // 100 }
2 构造块
将一个代码块写在一个类里面
运行方法:
public static void main(String[] args) { new Book(); }
Book类:
package com.test; public class Book { public Book() { System.out.println("Book类的构造方法"); } { //代码块写在类里面 System.out.println("Book类的构造块"); } }
运行结果:
我们发现构造块先运行,产生多个对象,构造块会出现多次。
3 静态块
如果代码块使用了static进行定义的话,那么就称它为静态块,有两种使用的情况
情况1: 在非主类中使用:
运行方法:
public static void main(String[] args) { new Book(); new Book(); new Book(); }
Book类
package com.test; public class Book { public Book() { System.out.println("Book类的构造方法"); } { //代码块写在类里面 System.out.println("Book类的构造块"); } static { System.out.println("Book类的静态块"); } }
运行结果:
从运行结果,我们可以看出,静态块的优先级高于构造块与构造方法。静态块一般是给静态属性初始化,但是使用比较少。
情况二:在主类中定义
static{ System.out.println("***********"); } public static void main(String[] args) { System.out.println("Hello World!"); }
运行结果:
静态块优先于主方法执行。在JDK1.7之前,可以没有主方法也能运行,只要有一个静态块也能运行,但是在1.7之后,这个BUG已经修复。
4总结
代码块能不用就不用,在编写测试可以使用静态块来做一些数据的初始化。
相关文章推荐
- java中静态代码块的用法 static用法详解
- Java静态代码块和构造方法执行顺序
- Java中的局部代码块、构造代码块、静态代码块
- 黑马程序员-java中构造函数、构造代码块、静态代码块及它们的初始化顺序
- Java中普通代码块,构造代码块,静态代码块区别及代码示例
- java 关于Java中静态代码块以及构造函数的执行先后顺序
- 由阿里巴巴一道笔试题看Java静态代码块、静态函数、动态代码块、构造函数等的执行顺序
- java中静态代码块的用法 static用法详解
- Java中静态代码块,普通代码块,构造函数详解
- 【Java面试题】16 静态代码块,main方法,构造代码块,构造方法
- java语言基础之4种代码块以及构造函数比较大集合-java基础精品笔记-作者:逝秋
- java静态代码块、构造方法、构造块的执行顺序
- Java之静态代码块、构造代码块、与构造函数的用法
- Java初始化顺序总结 - 静态变量、静态代码块、成员变量、构造函数
- java中静态代码块的用法 static用法详解
- Java中静态代码块的用法 static用法详解
- 【13】Java基础:java中的静态代码块,静态变量,静态方法
- 第十七、Java面向对象之构造函数与构造代码块
- Java基础--面向对象(封装、构造函数、构造代码块、this关键字)
- Java的4种代码块