
实例控制流是 Java 编程语言的一个基本概念,初学者和有经验的人都必须了解。在Java中,实例控制流是类内部成员的一步步执行过程。类内部存在的成员包括实例变量、实例方法和实例块。
每当我们执行 Java 程序时,JVM 首先查找 main() 方法,然后将类加载到内存中。更进一步,类被初始化,并且它的静态块(如果有)被执行。执行完静态块后,实例控制流程开始。在本文中,我们将解释什么是实例控制流。
上一节我们简单介绍了实例控制流程。在本节中,我们将通过示例程序详细讨论它。
实例控制流的流程涉及以下步骤:
第一步是从类的顶部到底部识别实例成员,如实例变量、实例方法和实例块
第二步是类的实例变量的执行。实例变量在类内部但在方法外部声明。一般来说,为了显示它们的值,我们需要定义一个构造函数或一个方法。
接下来,实例块将按照它们在类中出现的顺序由 JVM 执行。这些块是用于初始化实例变量的匿名块。
第四步,JVM调用类的构造函数来初始化对象。
进一步移动,调用实例方法来执行各自的操作。
最后调用垃圾收集器来释放内存。
下面的示例演示了实例控制流程的整个过程。
public class Example1 {
int x = 10; // instance variable
// instance block
{
System.out.println("Inside an instance block");
}
// instance method
void showVariable() {
System.out.println("Value of x: " + x);
}
// constructor
Example1() {
System.out.println("Inside the Constructor");
}
public static void main(String[] args) {
System.out.println("Inside the Main method");
Example1 exp = new Example1(); // creating object
exp.showVariable(); // calling instance method
}
}
Inside the Main method Inside an instance block Inside the Constructor Value of x: 10
下面的例子说明了父子关系中Instance的控制流程。父类的实例成员在子类的实例成员之前被执行。
// creating a parent class
class ExmpClass1 {
int x = 10; // instance variable of parent
// first instance block
{
System.out.println("Inside parent first instance block");
}
// constructor of parent class
ExmpClass1() {
System.out.println("Inside parent constructor");
System.out.println("Value of x: " + this.x);
}
// Second instance block
{
System.out.println("Inside parent second instance block");
}
}
// creating a child class
class ExmpClass2 extends ExmpClass1 {
int y = 20; // instance variable of child
// instance block of child
{
System.out.println("Inside instance block of child");
}
// creating constructor of child class
ExmpClass2() {
System.out.println("Inside child constructor");
System.out.println("Value of y: " + this.y);
}
}
public class Example2 {
public static void main(String[] args) {
// creating object of child class
ExmpClass2 cls = new ExmpClass2();
System.out.println("Inside the Main method");
}
}
Inside parent first instance block Inside parent second instance block Inside parent constructor Value of x: 10 Inside instance block of child Inside child constructor Value of y: 20 Inside the Main method
通过这篇文章,我们了解了Java中实例控制流的整个流程。这个过程总共有六个步骤。基本上,实例控制流告诉我们 Java 虚拟机如何执行类的成员。
以上是Java中的实例控制流程的详细内容。更多信息请关注PHP中文网其他相关文章!