How to use java to implement the effect of the ref keyword in C # (passing parameters by reference,
In the previous article (whether to pass a value or a reference when passing a Java parameter), we mainly analyzed that the passing of a java parameter is only passed by value but not by reference.
Let's take a look at Microsoft's C # documentation on the definition of transfer by reference (as follows): https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/ref#passing-an-argument-by-reference
So how does java implement the effect of the ref keyword in C # (passing parameters by reference?
Ideas
We can encapsulate the parameters to be passed, that is, to define a new class, so that the parameters to be passed become member variables of the new class. When passing parameters, we will pass the instances of the new class. To achieve the effect of the ref keyword.
Code demo
RefDemo. java
Public class RefDemo {public static void main (String [] args) {Person person1 = new Person (); PersonPack personPack = new PersonPack (); personPack. person = person1; // print the person System. out. println (personPack. person); change (personPack); // print the person System again. out. println (personPack. person);} public static void change (PersonPack personPack) {Person person2 = new Person (); personPack. person = person2 ;}/ *** Person class */class Person {}/ *** packaging class: PersonPack */class PersonPack {public Person person ;}
Running result:
We can see that the address values of the two printed persons are different. That is, after the change () method is called, the person references (points to) another object!
You are welcome to repost, but please keep the original source of the article
Address: http://www.cnblogs.com/nnngu/p/8300164.html