参数传值分为:值传递以及引用传递(地址传递)。(个人理解-勿喷)
参数分为基本类型,对象等。
1.基本类型(8大类型:int/float/double/char/long/boolean/byte/short)
例子:
/**
* @description:
* @author: lc
* @time: 2018/2/23 0023
*/
public class Test01 {
public static void main(String[] args) {
int count=1;
System.out.println("改变前...count="+count);
change(count);
System.out.println("改变后...count="+count);
}
public static void change(int count){
count=count+1;
}
}
结果:
改变前...count=1
改变后...count=1
Process finished with exit code 0
说明:对于基本类型,只是把值(副本)传递进去。由于String是不可变对象,所以在这里和基本类型一样的效果
2.对象
例子
Student类:
/**
* @description:
* @author: lc
* @time: 2018/2/23 0023
*/
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试类
/**
* @description:
* @author: lc
* @time: 2018/2/23 0023
*/
public class Test {
public static void main(String[] args) {
Student s1=new Student();
s1.setName("李四");
change1(s1);
System.out.println("s1.getName():"+s1.getName());
}
public static void change1(Student s2){
Student s3=new Student();
s3.setName("张三1");
s2.setName("张三");
s2=s3;
}
}
结果:
s1.getName():张三
Process finished with exit code 0
结果为什么是张三?看下面分析
分析图