Anonymous object: When creating an object, no variable is used to save the address in the heap
eg: new student();
Usage scenario: It
can only be used directly when it is created, and can only be used once.
eg: start thread: new Thread().start();
Function:
can save resources, because GC will recycle anonymous objects from time to time.
(GC is a garbage collection mechanism, the main object of recycling is anonymous objects)
==================================================
Four steps of encapsulation:
- Private member variables (modify member variables with private)
- Provide getXxx() and void setXxx(...) methods for each member variable. If the current member variable type is boolean type, change getXxx() to isXxx()
- No-parameter construct
- This class is decorated with public
======================================================
The main two functions of this
1. Solve the ambiguity between member variables and local variables
public void setName(String name) {
this.name = name;//直接从成员变量位置找name
//name=name//这里就近原则,第一个name就是参数name,打印为null
}
2. Reuse other construction methods to simplify the code for assigning member variables
public User(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public User(String name, String phone, boolean vip) {
this(name,phone);
this.vip = vip;
}
Extension: Fields have default values, such as the initial password of the account.
Entity class
public User(String name) {
this(name,"123456");
}
public User(String name, String pwd) {
this.name=name;
this.pwd = pwd;
}
Test class
public class UserTest {
public static void main(String[] args) {
//通过有参构造进行赋值,初始账户密码均为123456
User shp=new User("小明");
User shp=new User("小红");
User shp=new User("小花");
}
}
=================================================
When creating an object, the bytecode file of this class will be loaded into the memory area
of the metaspace ; the created object is in the heap, and the corresponding variable of the method in the stack frame stores the address of the object