zoukankan      html  css  js  c++  java
  • Java中的代码块

    代码块

    • 普通代码块
    • 构造代码块
    • 静态块
    • 同步代码块

    普通代码块

    为了在方法里面编写过多的变量,防止变量重复,可以用代码块进行隔离。

    package org.lyk.main;

    public class Main

    {

         public static void main(String[] args)

         {

               {

                    int num = 3;

                    System.out.println(num);

               }

               int num = 3;

               System.out.println(num);

         }

    }

    构造代码块

    如果现在将一个代码块写在了一个类里面,那么该代码块成为构造块。

    • 构造块优先于构造方法执行
    • 如果产生多次对象,那么构造块代码每次都会执行
    • 一般说来,构造块无实际意义

    package org.lyk.entities;

    public class Book

    {

         private String title;

         private float price;

          

         public Book(String title, float price)

         {

               super();

               this.title = title;

               this.price = price;

               System.out.println("2.构造方法");

         }

        

         {

               System.out.println("1. 构造块");

         }

    }

    静态块

    如果一个代码块使用了static进行修饰的话,那么就成为静态块。

    静态块的使用分为两类:

    在非主类使用

    静态块优先于构造块执行,不管有多少个实例化对象,静态块只执行一次。其作用是为类中的static变量初始化。

    package org.lyk.entities;

    public class Book

    {

         static int totalCount ;

         private String title;

         private float price;

          

         public Book(String title, float price)

         {

               super();

               this.title = title;

               this.price = price;

               System.out.println("2.构造方法");

         }

        

         static

         {

               System.out.println("1. 静态块");

               totalCount=0;

         }

    }

    主类中使用

    静态块将优先于主方法执行。

    package org.lyk.main;

    public class Main

    {

         static

         {

               System.out.println("主方法中的静态块");

         }

         public static void main(String[] args)

         {

               System.out.println("主方法");

         }

    }

    总结:

    代码块在开发中能不用就别用。但如果非要使用,那么唯一好用的就是静态块。

  • 相关阅读:
    基于tensorflow的简单线性回归模型
    msm8909平台JEITA配置和bat-V therm表合入
    开始点滴积累
    消息队列中间件(一)介绍
    Ubuntu18 的超详细常用软件安装
    IO通信模型(三)多路复用IO
    IO通信模型(二)同步非阻塞模式NIO(NonBlocking IO)
    IO通信模型(一)同步阻塞模式BIO(Blocking IO)
    Web笔记(二)Tomcat 使用总结
    const in C/C++
  • 原文地址:https://www.cnblogs.com/kuillldan/p/5884793.html
Copyright © 2011-2022 走看看