Java中的非静态块。
甲静块是代码使用静态关键字的块。通常,这些用于初始化静态成员。JVM在类加载时在main方法之前执行静态块。
示例
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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿