1. How to understand basic data types and reference data types
Basic data types: numeric (int, long, etc.), character (char), Boolean (boolean)
Reference data types: array (array), class (class), interface (interface)
The variable name of the basic data type corresponds to the variable itself.
A reference in a reference data type is an address that points to its instance object.
2. How to understand references and objects
For the code below:
public class Student{
public static void main(String[] args){
//看下面这句代码
Student s = new Student();
}
}
In this code, s
it is a reference, new Student()
which is the operation of creating an instance object, then s
what is stored in this reference is an address, which points to its object Student
.
Look at the picture below:
3. How to understand local variables, member variables, static variables
public class Student {
//s2是成员变量,它存储在堆中
Student s2 = new Student();
//s3是静态变量,也叫类变量,它存储在方法区
static Student s3 = new Student();
public static void main(String[] args) {
//s1是局部变量,它存储在栈中
Student s1 = new Student();
}
}
Local variables are stored on the stack (s1 is a local variable):
Member variables are stored on the heap (s2 is a member variable):
Static variables are stored in the method area (s3 is a static variable):
4. Execution process of recursive method
The recursive function in the figure is to find the factorial of n, we set n to be 5, then it is to find the factorial of 5, and the result is 120.
The blue arrow indicates the process of "passing" downward, and the red arrow indicates the process of "returning".
5. The difference between static method and ordinary method
Ordinary methods are also called instance methods, which have this and are related to instances.
Static methods are also called class methods, without this, and have nothing to do with instances.
In other words, static methods can be used through the class itself before the object is created, while ordinary methods must be called through the new object.
Static methods are called directly through the class:
public class Student {
public static void read(){
System.out.println("读这句话");
}
}
public class Test {
public static void main(String[] args) {
//通过类直接调用
Student.read();
}
}
Ordinary methods must be called by first creating an instance object of the class
public class Student {
public void read(){
System.out.println("写这句话");
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student();
//创建实例后才能调用
student.read();
}
}