欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

java中參數(shù)傳遞方式詳解

java中參數(shù)傳遞方式詳解

成都創(chuàng)新互聯(lián)主營東蘭網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,手機(jī)APP定制開發(fā),東蘭h5微信平臺小程序開發(fā)搭建,東蘭網(wǎng)站營銷推廣歡迎東蘭等地區(qū)企業(yè)咨詢

java新手入門面臨的一個(gè)經(jīng)典的話題,本文意在終結(jié)這個(gè)話題,java中有說法:Java里面參數(shù)傳遞都是按值傳遞,怎么理解這句話?用文字說明恐怕不容易說明白,說明白恐怕也難以想明白。

前提

先明確一下,按值還是按引用的概念,它是來自c++語言,引用不是漢語詞典中的一個(gè)詞,而是c++的概念——“&”這個(gè)符號還記得吧?

為什么有這個(gè)話題呢?其一,是對按引用傳遞理解不透徹;其二,諸多java書籍及討論論點(diǎn)并沒有切中要害。

一句話概括,按值傳參還是按引用傳參,既然是參數(shù)傳遞方式,那么只針對形參和實(shí)參,這里說的是參數(shù)本身,不是參數(shù)對象的子對象或?qū)O子對象。

有了前提,上c++代碼:

#include <iostream>

using namespace std;

class User
{
 private:
  int m_id;
 public:
  User(int id=0){m_id = id;}
  void setId(int id){m_id = id;}
  int getId(){return m_id;}
};

void test0(User t){//按值傳參
 User s;
 t = s;
 t.setId(1002);
 cout << "test1:" << t.getId() << endl;
}

void test1(User *t){//按值傳參
 t = new User();//指針指向了一個(gè)新對象,外面實(shí)參沒變
 t->setId(1002);
 cout << "test1:" << t->getId() << endl;
}

void test2(User* & t){//按引用傳參
 t = new User();//指針指向了一個(gè)新對象,外面實(shí)參也跟著變了
 t->setId(1002);
 cout << "test2:" << t->getId() << endl;
}

int main(int argc, char const *argv[]) {
 cout<< "\npass by ref:"<<endl;
 User* t = new User();
 t->setId(1001);
 cout << t->getId() << endl;
 test2(t);
 cout << t->getId() << endl;

 cout<< "\npass by value:"<<endl;
 t = new User();
 t->setId(1001);
 cout << t->getId() << endl;
 test1(t);
 cout << t->getId() << endl;
 return 0;
}

輸出結(jié)果:

pass by ref:
1001
test2:1002
1002

pass by value:
1001
test1:1002
1001

c++小結(jié):

按值傳遞,那么在函數(shù)內(nèi)修改了形參指向一個(gè)新對象,外面的實(shí)參不受影響。

按引用傳遞,那么在函數(shù)內(nèi)修改了形參指向一個(gè)新對象,外面的實(shí)參也變了。

旨在說明問題,代碼可能有內(nèi)存泄漏。

上java:

package com.pollyduan.bean;

@Data
public class User {
 private Integer id;

 public static void testObject(User t){
  t=new User();//指向了一個(gè)新對象,外面實(shí)參沒變
  t.setId(1002);
  System.out.println("testObject="+t);
 }

 @Test
 public void testObject(){
  User user=new User();
  user.setId(1001);
  System.out.println("user="+user);
  testObject(user);
  System.out.println("user="+user);
 }
}

輸出結(jié)果:

user=User(id=1001)
testObject=User(id=1002)
user=User(id=1001)

java小結(jié):

跟c++的邏輯比較一下,請自行對號入座。

網(wǎng)站名稱:java中參數(shù)傳遞方式詳解
新聞來源:http://chinadenli.net/article12/ihodgc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站網(wǎng)站導(dǎo)航定制網(wǎng)站App設(shè)計(jì)網(wǎng)站營銷企業(yè)網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)