How to use java to implement the effect of the ref keyword in C # (passing parameters by reference,

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.