本文用一下代码说明:
Java代码
简单字符串String:
- package luojing;
- public class StringDemo
- {
- public static void main(String[]args)
- {
- String str=new String("hello");
- //调用函数改变str的值
- change(str);
- System.out.println(str);
- }
- public static void change(String str1)
- {
- str1+="luojing";
- }
- }
StringBuffer:
- public class StringDemo
- {
- public static void main(String[]args)
- {
- StringBuffer str=new StringBuffer("hello");
- //调用函数改变str的值
- change(str);
- System.out.println(str);
- }
- public static void change(StringBuffer str1)
- {
- str1.append("luojing");
- }
- }
将上面的StringBuffer换成我们自己定义的对象:
- public class test
- {
- public static void main(String[] args)
- {
- Demo demo=new Demo("hello");
- //调用函数该变demo.name的值
- change(demo);
- System.out.println(demo.getName());
- }
- public static void change(Demo d)
- {
- d.setName("luojing");
- }
- }
- class Demo
- {
- private String name;
- public Demo(String s)
- {
- name=s;
- }
- public String getName()
- {
- return name;
- }
- public void setName(String str)
- {
- name=str;
- }
- }
我们再对change()方法做一些修改:
- package luojing;
- public class test
- {
- public static void main(String[] args)
- {
- Demo demo=new Demo("hello");
- //调用函数该变demo.name的值
- change(demo);
- System.out.println(demo.getName());
- }
- public static void change(Demo d)
- {
- Demo d1=new Demo("hello java");
- d=d1;
- }
- }
- class Demo
- {
- private String name;
- public Demo(String s)
- {
- name=s;
- }
- public String getName()
- {
- return name;
- }
- public void setName(String str)
- {
- name=str;
- }
- }
- class Foo {
- private int x;
- public Foo(int x) {
- this.x = x;
- }
- public void setX(int x) {
- this.x = x;
- }
- public int getX() {
- return x;
- }
- }
- public class Submit {
- static Foo fooBar(Foo foo) {
- foo = new Foo(100);
- return foo;
- }
- public static void main(String[] args) {
- Foo foo = new Foo(300);
- System.out.print(foo.getX() + "-");
- Foo fooFoo = fooBar(foo);
- System.out.print(foo.getX() + "-");
- System.out.print(fooFoo.getX() + "-");
- foo = fooBar(fooFoo);
- System.out.print(foo.getX() + "-");
- System.out.print(fooFoo.getX());
- }
- }