Java 中的非静态块。
静态块是带静态关键字的代码块。通常,这些静态块用于初始化静态成员。在类加载时,JVM 在主方法之前执行静态块。
示例
public class MyClass {
static{
System.out.println("Hello this is a static block");
}
public static void main(String args[]){
System.out.println("This is main method");
}
}输出
Hello this is a static block This is main method
实例初始化块
与静态块类似,Java 也提供实例初始化块,该块用于初始化实例变量,以替代构造函数。
每当你定义一个初始化块时,Java 会将其代码复制到构造函数中。因此,你还可以使用它们在类的构造函数之间共享代码。
示例
public class Student {
String name;
int age;
{
name = "Krishna";
age = 25;
}
public static void main(String args[]){
Student std = new Student();
System.out.println(std.age);
System.out.println(std.name);
}
}输出
25 Krishna
在一个类中,你还可以有多个初始化块。
示例
public class Student {
String name;
int age;
{
name = "Krishna";
age = 25;
}
{
System.out.println("Initialization block");
}
public static void main(String args[]){
Student std = new Student();
System.out.println(std.age);
System.out.println(std.name);
}
}输出
Initialization block 25 Krishna
你还可以定义父类中的实例初始化块。
示例
public class Student extends Demo {
String name;
int age;
{
System.out.println("Initialization block of the sub class");
name = "Krishna";
age = 25;
}
public static void main(String args[]){
Student std = new Student();
System.out.println(std.age);
System.out.println(std.name);
}
}输出
Initialization block of the super class Initialization block of the sub class 25 Krishna
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP