Object-oriented
Design objects and use them
Category: A description of common features (design drawing)
Object: is a real specific instance
-
Javabean class: A class used to describe a type of thing. The main method is not written in the Javabean class.
Note: The first letter of the class name should be capitalized, see the name and meaning, (camel mode)
Note: In actual development, it is recommended that a file defines a class class
Code:
package .Demo01; public class GirlFriend { //property String name; int age; String gender; //Behavior public void eat(){ ("Eating"); } public void sleep(){ ("Sleeping"); } }
package .Demo01; public class GirlFriendTest { public static void main(String[] args) { //Create a girlfriend GirlFriend gf1 = new GirlFriend(); //Assignment = 18; = "female"; = "Xiaoqi"; //Output (); (); (); //Calling method (); (); ("--------------------"); //new the second object GirlFriend gf2 = new GirlFriend(); //Assignment = 18; = "female"; = "Xiaoqing"; //Output (); (); (); //Calling method (); (); } }
Package
They are the three major features of object-oriented (encapsulation, inheritance, polymorphism)
-
What the object represents must be encapsulated and the corresponding behavior of the data must be provided.
Case:
People close the door
This door is closed by itself, and people just give the door a force.
Private keyword
is a permission modifier
Members can be modified (member variables and member methods)
-
Members modified by private (private) can only be accessed in this class
example:
package ; public class Test { private int age; // private: private //set assignment public void setAge(int a){ if(a>=10 && a<= 50){ age = a; }else{ ("Illegal Data"); } } //get(get) public int getAge(){ return age; } }
For member variables modified by private, if they need to be used by other classes, they must provide corresponding operations.
Provide the "setXxx(parameter)" method to assign values to member variables, and the method is modified with public
Provide the "getXxx()" method to get the value of member variables, and the method is modified with public (public)
The principle of proximity and this keywords
Sample code:
package .test01; public class GirlFriend { //Member variable private int age; public void method() { //Local variables (method variables) int age = 10; //(age); //The principle of proximity (I will use whoever is close to me) (); //this keyword The age here is the age of member variable } }
package .test01; public class GirlFriendTest { public static void main(String[] args) { //Create a GirlFriend object //Format: Class name Object name = new Class name(); //example GirlFriend gf1 = new GirlFriend(); (); } }
The role of this keyword
- Distinguish between member variables and local variables
Construction method
In Java, constructors are special methods used to create objects and initialize objects. The construction method has the following precautions:
The name of the constructor must be exactly the same as the class name, and there is no return type (including void), they cannot be called explicitly, but are automatically called when the object is created.
If no constructor is defined in the class, the Java compiler will automatically generate a default parameterless constructor. If a constructor is defined in the class, the compiler will not automatically generate the default constructor.
Multiple constructors can be defined, which can have different parameter lists (different number, type, or order of parameters), which is called overloading of methods.
The constructor can have access modifiers (such as public, private, protected) to control access rights to the constructor. In general, the constructor should use a public modifier so that other classes can instantiate the object.
In a constructor, you can use the keyword super to call the constructor of the parent class to initialize the member variables of the parent class when creating a child object.
Constructors can use this keyword to call other constructors in the same class for reuse between constructors.
The constructor can throw exceptions, but it is not generally recommended to throw a detected exception in the constructor. Instead, the exception should be handled or unchecked exceptions should be used in the constructor.
The constructor can perform any initialization operations, such as initializing the member variables of an object, calling other methods, etc.
It should be noted that the main purpose of the constructor is to perform initialization operations when creating objects, so too much logic or complex calculations should be avoided in the constructor. If complex initialization operations are required, consider using static factory methods or other design patterns instead of construction methods.
Standard JavaBean
Class names need to be known
Member variables are modified with private
-
Provide at least two construction methods
Parameterless construction method
Construction method with all parameters
-
Member Methods
Provide setXxx() and getXxx() corresponding to each member variable
If there are any other behaviors, please write it
shortcut key
// alt + insert (quickly generate the JavaBean standard class to construct methods, set methods and get methods that do not participate in all parameters)
Plugin
PTG generates standard JavaBeans in one second
Object memory diagram
An object memory diagram
When an object is created in Java, it allocates a continuous piece of memory space in heap memory to store the object's data. Here is a more detailed memory diagram example of Java objects:
-
Object Header: The object header is the part used to store the metadata of an object. It usually contains the following information:
- Type Pointer: Metadata to the class to which the object belongs.
- Hash Code: The hash code of the object, used to support the hash table operation of the object.
- Lock Information: used to support synchronization and concurrent operations of objects.
Instance Variables: An instance variable, also known as a member variable or field, is the data part of an object. They are variables defined in the class that store the state and properties of an object. Each instance variable occupies a certain amount of memory space, and the specific size depends on the type and alignment requirements of the variable.
When creating an object, the Java virtual machine performs the following steps:
Allocate memory: The Java virtual machine allocates a continuous piece of memory space in heap memory to store object data.
Initialize object header: Java virtual machine initializes the fields of the object header to default values, such as type pointers, hash codes, and lock information.
Initialize instance variables: Java virtual machine initializes the value of the instance variable to the default value, such as the numeric type is 0, the Boolean type is false, and the reference type is null.
-
Execute the constructor: The Java virtual machine calls the constructor of the object to perform further initialization operations, and the specific value of the instance variable can be set in the constructor.
Note: The above memory diagrams and steps are based on the traditional Java object model, and the specific implementation may vary depending on the implementation of the Java virtual machine. In addition, Java has other memory areas, such as stack memory, method areas, etc., which are used to store different types of data and execute other operations of programs.
Two references point to the same object
In Java, this can be achieved by pointing two reference variables to the same object. When two references point to the same object, they actually refer to the same memory address, so they can access and modify the same object data.
Here is a sample code that demonstrates how to create two references in Java pointing to the same object:
public class Main { public static void main(String[] args) { // Create an object MyClass obj = new MyClass(); // Create two references to point to the same object MyClass ref1 = obj; MyClass ref2 = obj; // Modify the object's data ("Hello, World!"); // Access and modify the same object data through two references (()); // Output: Hello, World! (()); // Output: Hello, World! } } class MyClass { private String data; public void setData(String data) { = data; } public String getData() { return data; } }
In the example above,
ref1
andref2
are two reference variables, both point toobj
The same referencedMyClass
Object. Through these two reference variables, we can access and modify the same object data.It should be noted that when an object has no reference to it, it becomes a garbage object in Java and memory is reclaimed by the garbage collector. Therefore, when pointing to the same object with multiple references, you need to be careful to make sure that it is placed in time when no reference is needed
null
, so that the garbage collector can recycle objects that are no longer in use.The difference between basic data types and referenced data types
Storage method: The value of the basic data type is stored directly in a variable, while the variable that references the data type stores the reference of the object (memory address).
-
Size and Default: The base data type has a fixed size and default value, while the size of the referenced data type depends on the size of the object, and the default value is null.
- The size of the basic data type is fixed and not affected by the specific platform. For example, the int type always takes up 4 bytes.
- The size of the referenced data type depends on the size of the referenced object. For example, a reference variable might point to a small object or a large object.
- The default value of the basic data type is determined based on its type. For example, the default value of int type is 0, and the default value of boolean type is false.
- The default value of the reference data type is null, indicating that the reference variable is not currently pointing to any object.
-
Passing method: The basic data type is passed by value when passing method parameters, while the reference data type is passed by reference when passing method parameters.
- When the base data type is passed as a method parameter, a copy of the actual value is passed. Modifying parameters inside the method will not affect the original value.
- When passing the referenced data type as a method parameter, a copy of the reference is passed. Modifying parameters inside the method will affect the original object.
-
Memory management: variables of basic data types directly store data values, and memory management is processed by the compiler or interpreter; while variables referencing data types store references to objects, creation and destruction of objects are manually managed by developers or automatically processed by garbage collectors.
- Variables of basic data types allocate memory on the stack, and their life cycle is controlled by the program.
- Objects that reference data types allocate memory on the heap, and their life cycle is manually managed by developers or automatically processed by Java's garbage collector.
It should be noted that the basic data types in Java include boolean, byte, short, int, long, float, double and char, while all other types belong to reference data types, including classes, interfaces, arrays, and enums.
The memory principle of this keyword
Function: Used to distinguish local and member variables
The essence of this: the address value of the method caller
In Java,
this
The keyword represents a reference to the current object. It can be used in instance methods and constructors to refer to the object that is currently executing the method.this
The memory principle of keywords is as follows: When an object is created, the Java virtual machine allocates memory space for the object on the heap and stores the object's instance variables in that memory space.
When an instance method of an object is called, the Java virtual machine passes the reference of the current object to the method as a hidden parameter. This hidden parameter is
this
A reference to the current object represented by the keyword.Inside the method, you can use
this
Keywords to access the instance variables and instance methods of the current object. passthis
Keywords can explicitly specify members of the current object to avoid conflicts with local variables or parameters.When the method is executed,
this
The role of keywords is over. It does not take up extra memory space, but is released after the method call is finished.
It should be noted that each instance method has an implicitthis
parameter, but it does not appear explicitly in the method's parameter list. The compiler will automaticallythis
The parameters are added to the method's parameter list for use inside the method.
To sum up,this
Keywords are used in Java to reference the current object. They do not take up extra memory space, but are passed to the instance method as an implicit parameter. passthis
Keywords, you can access the instance variables and instance methods of the current object.
The difference between member variables and local variables
In Java, member variables (also known as instance variables) and local variables are two different types of variables, which have the following differences:
Scope: Member variables are defined in a class and can be accessed in various methods throughout the class. Local variable definitions are only valid within the scope in which they are located.
Lifecycle: The lifecycle of a member variable is the same as the lifecycle of an object, and is initialized when the object is created until the object is destroyed. The life cycle of local variables is limited to the scope where they are located. After leaving the scope, local variables will be destroyed.
Default: Member variables are assigned a default value. For example, the default value of the integer type member variable is 0, and the default value of the Boolean type member variable is false. Local variables have no default values and must be explicitly initialized before use.
Access modifier:Member variables can be accessed using different access modifiers (such as public, private, protected) to control their visibility. Local variables cannot use access modifiers, and their visibility is limited to their scope.
Memory allocation: Member variables allocate memory space when object is created, and each object has a copy of member variables. Local variables allocate memory space when a method call or code block is executed, and each call or execution will create a new local variable.
It should be noted that member variables and local variables can have the same name, but within the same scope, local variables will override member variables with the same name. If you need to access a member variable, you can use the keyword "this" to refer to the member variable of the current object.
Summarize
This is the end of this article about classes and objects in Java. For more related classes and objects in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!