What is the use of this in java
1. This calls the current attribute: its main The function is that when you need to initialize the data in the class, you can assign the value through this instead of defining a variable for assignment, which is more conducive to the reading and understanding of the code (recommended tutorial: java tutorial)
class Book{//定義書的類 private String name;//書本名字 private int price;//書本價格 public Book(String name,int price){ //使用this對類的數據進行初始化 this.name = name; this.price = price; } /*public Book(String n,int p){ //若不使用this關鍵字只能這樣進行賦值,不利于將變量與屬性統(tǒng)一起來 name = n; price = p; }*/ public String getInfo(){ return "書籍:" + name + ",價格:" + price; } } public class ThisDemo{ public static void main(String args[]){ System.out.printIn(new Book("Java",89.9).getInfo()) } }
2. this calling method (ordinary method, constructor method)
(1) Ordinary method:
class Book{//定義書的類 private String name;//書本名字 private int price;//書本價格 public Book(String name,int price){//使用this對類的數據進行初始化 this.name = name; 6 this.price = price; this.print();//調用本類普通方法,雖然可以不用使用this也可以進行本類普通方法的調用,但是好的習慣最好應該加上,目的是可以區(qū)分方法的定義來源 } public String getInfo(){ return "書籍:" + name + ",價格:" + price; } public void print(){ System.out.printIn("***********"); } } public class ThisDemo{ public static void main(String args[]){ System.out.printIn(new Book("Java",89.9).getInfo()) } }
(2) Constructor method: The difference between ordinary methods and constructor methods is that the constructor method can only be used once after creation to initialize data, while the ordinary method is It can be called multiple times after creation.
When you need to use the constructor method to output the same repeated content, if you do not use the this keyword, you can only use the following code:
class Book{//定義書的類 private String name;//書本名字 private int price;//書本價格 public Book(){//無參構造 System.out.printIn("*************"); } public Book(String name){//一參構造 System.out.printIn("*************"); this.name = name; } public Book(String name,int price){//二參構造 System.out.printIn("*************"); this.name = name; this.price = price; } public String getInfo(){ return "書籍:" + name + ",價格:" + price; } } public class ThisDemo{ public static void main(String args[]){ System.out.printIn(new Book("Java",89.9).getInfo()) } }
Obviously, this greatly wastes the number of lines of code, but should Use this to call the constructor method as follows:
class Book{//定義書的類 private String name;//書本名字 private int price;//書本價格 public Book(){//無參構造 System.out.printIn("*************"); } public Book(String name){//一參構造 this();//調用本類中的無參構造 this.name = name; } public Book(String name,int price){//二參構造 this(name);//調用本類中的一參構造 this.price = price; } public String getInfo(){ return "書籍:" + name + ",價格:" + price; } } public class ThisDemo{ public static void main(String args[]){ System.out.printIn(new Book("Java",89.9).getInfo()) } }
Note: The call to this must be the first statement in the constructor method, otherwise an error will occur. Of course, the constructor method cannot be called in an ordinary method.
The most important thing is that calling this cannot form a loop, that is, it cannot form a recursive call without an exit.
3. this represents the current method
class Book{ public void fun(){ System.out.printIn("FUN方法"+this); } } } public class ThisDemo{ public static void main(String args[]){ Book b1 = new Book(); System.out.printIn("MAIN方法"+b1); b1.fun();//有b1調用fun方法(this = b1) //兩個輸出結果的地址一樣,代表著此時this代表著b1 System.out.printIn("*************") Book b2 = new Book(); System.out.printIn("MAIN方法"+b2); b2.fun();//此時輸出結果和b2一樣 } }
Throughout the process, the definition of this has not changed. As long as a certain object calls a method in this class, at this time this represents the currently executing object.
The above is the detailed content of What is the use of this in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa
