Java Novice Introduction to face a classic topic, this article is intended to end this topic, Java has the saying: Java里面参数传递都是按值传递
, how to understand this sentence? I'm afraid it's not easy to explain in words, but I'm afraid it's hard to understand white.
Premise
First of all, by value or by reference concept, it is from the c++
language, reference is not a word in the Chinese dictionary, but the concept of C + +-"&" This symbol remember it?
Why do you have this topic? One is that there is not a thorough understanding of by-reference, and the other is that many Java books and discussion arguments are not hitting the point.
In a nutshell, the parameter is passed by value or by reference, and since it is a parameter passing method, it is only for formal parameters and arguments, which is the argument itself, not the child or grandson object of the Parameter object.
With the premise, on the C + + code:
#include <iostream>using namespace STD;classuser{Private:intm_id; Public: User (intId=0{m_id = ID;}voidSetId (intID) {m_id = ID;}intGetId () {returnm_id;}};voidTest0 (User t) {//By value-Pass parameterUser s; t = s; T.setid (1002);cout<<"Test1:"<< T.getid () << Endl;}voidTest1 (User *t) {//By value-Pass parametert =NewUser ();//The pointer points to a new object, the outside argument does not changeT->setid (1002);cout<<"Test1:"<< T->getid () << Endl;}voidTest2 (user* & T) {//By referencet =NewUser ();//The pointer points to a new object, and the outside argument changes.T->setid (1002);cout<<"Test2:"<< T->getid () << Endl;}intMainintargcChar Const*argv[]) {cout<<"\npass by ref:"<<endl; user* T =NewUser (); T->setid (1001);cout<< T->getid () << Endl; Test2 (t);cout<< T->getid () << Endl;cout<<"\npass by value:"<<endl; t =NewUser (); T->setid (1001);cout<< T->getid () << Endl; Test1 (t);cout<< T->getid () << Endl;return 0;}
Output Result:
by ref:1001test2:10021002byvalue:1001test1:10021001
C + + Summary:
Passed by value, the parameter is modified within the function to point to a new object, and the outside arguments are unaffected.
Passed by reference, the parameter is modified within the function to point to a new object, and the outside argument is changed.
Designed to illustrate the problem, the code may have a memory leak.
On Java:
PackageCom.pollyduan.bean;@Data Public class User { PrivateInteger ID; Public Static void Testobject(User t) {t=NewUser ();//point to a new object, the outside argument does not changeT.setid (1002); System.out.println ("testobject="+T); }@Test Public void Testobject() {User user=NewUser (); User.setid (1001); System.out.println ("User="+user); Testobject (user); System.out.println ("User="+user); }}
Output Result:
user=User(id=1001)testObject=User(id=1002)user=User(id=1001)
Java Summary:
Compare with the logic of C + +, please take your own seat.
How to pass a parameter in Java topic end instance