标签:tor 构造函数 模块 class 注意 zed content exe tps
[初始化块包含创建实例时始终执行的代码。它用于声明/初始化类的各种构造函数的公共部分。例如,
import java.io.*; public class GFG { ????// Initializer block starts.. ????{ ????????// This code is executed before every constructor. ????????System.out.println("Common part of constructors invoked !!"); ????} ????// Initializer block ends ? ????public GFG() ????{ ????????System.out.println("Default Constructor invoked"); ????} ????public GFG(int x) ????{ ????????System.out.println("Parametrized constructor invoked"); ????} ????public static void main(String arr[]) ????{ ????????GFG obj1, obj2; ????????obj1 = new GFG(); ????????obj2 = new GFG(0); ????} }
输出:
Common part of constructors invoked!! Default Constructor invoked Common part of constructors invoked!! Parametrized constructor invoked
我们可以注意到,无论何时调用构造函数(在构造函数的内容之前),都会执行初始化块的内容。
??Java 面向对象标签:tor 构造函数 模块 class 注意 zed content exe tps
原文地址:https://www.cnblogs.com/breakyizhan/p/13286100.html