Java 实例控制流
实例控制流是Java编程语言的一个基本概念,初学者和经验丰富的程序员都必须了解。在Java中,实例控制流是类中成员执行的逐步过程。类中存在的成员包括实例变量、实例方法和实例块。
每当我们执行Java程序时,JVM首先查找main()方法,然后将类加载到内存中。接下来,类被初始化,并且如果存在静态块,则执行静态块。在执行静态块之后,实例控制流开始。在本文中,我们将解释什么是实例控制流。
Java 实例控制流
在上一节中,我们简要介绍了实例控制流。在本节中,我们将通过示例程序详细讨论它。
实例控制流的过程涉及以下步骤:
第一步是从上到下识别类的实例成员,例如实例变量、实例方法和实例块。
第二步是执行类的实例变量。实例变量声明在类内但方法外。通常,要显示它们的值,我们需要定义一个构造函数或方法。
接下来,实例块按其在类中出现的顺序由JVM执行。这些块是用于初始化实例变量的匿名块。
在第四步中,JVM调用类的构造函数来初始化对象。
接下来,调用实例方法以执行其各自的操作。
最后,调用垃圾收集器来释放内存。
示例 1
以下示例演示了实例控制流的整个过程。
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
示例 2
以下示例说明了父子关系中的实例控制流。父类的实例成员在子类实例成员之前执行。
// 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虚拟机如何执行类的成员。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP