是java通过引用传递

时间:2015-07-08 13:53:53

标签: java

我有一个类,它传递对象,原始。任何人都可以解释这个

public class TestObj {
String name;
int age;

public TestObj(String name, int age) {
    this.name = name;
    this.age = age;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

@Override
public String toString() {
    return "TestObj{" + "name=" + name + ", age=" + age + '}';
}

}

主要班级

public class Test {

public static void main(String[] args) {
    Test t = new Test();

    TestObj obj = new TestObj("James", 25);
    System.out.println("************* Output ****************");
    System.out.println(obj);
    t.setName(obj);
    t.setAge(obj);
    System.out.println(obj);

    String a = "Hai Test";
    System.out.println(">> :: " + a);
    t.setString(a);
    System.out.println(":: " + a);

    int x = 10;
    System.out.println("------- " + x);
    t.setInt(x);
    System.out.println("------- " + x);

}

public void setInt(int y) {
    y = 25;
}

public void setString(String x) {
    x = "Did i changed my Data";

}

public void setName(TestObj obj1) {
    obj1.setName("I got Changed");
}

public void setAge(TestObj obj1) {
    obj1.setAge(35);
}

}  

*************输出****************

  
    

TestObj {name = James,age = 25}

         

TestObj {name =我被改变了,年龄= 35}

         

:: Hai Test

         

:: Hai Test

         

------- 10

         

------- 10

  

1 个答案:

答案 0 :(得分:1)

java是'按值传递'。总是。但是当参数是一个对象时,该值是一个引用(一个对象的地址),而不是该对象本身