//构造块:直接在类中定义且没有加static关键字的代码块称为{}构造代码块.构造代码块在创建对象时被调用,每次创建对象都会被调用,并且构造代码块的执行次序优先于类构造函数.
{
System.out.println("第一代码块");
}
System.out.println("构造方法");
System.out.println("第二构造块");
public static void main(String[] args){
/**
执行结果:
第一代码块
第二构造块
构造方法
构造方法*/
代码如下
public class Rectangle {
private double length = 1;
private double width = 1;
public Rectangle(){}
public Rectangle(double length,double width){
this.length = length;
this.width = width;
public double getArea(){
return length*width;
public double getPerimeter(){
* @author geek
*/
public class Cylinder {
private double radius,
height;
public Cylinder() {
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
public double getVolume(){
return Math.PI*radius*radius*height;
public static void main(String[] args) {
System.out.println("半径"+c.radius);
System.out.println("高"+c.height);
构造函数:执行时间比构造代码块时间晚,也是在对象初始化的时候运行.没有返回值,构造函数名称和类名一致.
构造代码块:执行时间比静态代码块晚,比构造函数早,和构造函数一样,只在对象初始化的时候运行.没有名字、参数和返回值.
静态代码块:最早执行,类被载入内存时执行,只执行一次.没有名字、参数和返回值,有关键字static.
静态代码块只会在类被载入内存时加载一次,是最先执行的,然后是构造代码块,最后才是构造函数.构造代码块和构造函数都是在对象创建的时候执行,有几个对象就会执行几次.
以上就是土嘎嘎小编为大家整理的java构造代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!