概述
实体直接作为参数传递,最后实体参数的属性值也会改变
1.新建一个Student实体类
public class Student {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
}
2.新建一个测试类
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Student stua = new Student("zhangsan",15);
System.out.println("stua---->"+stua);
Student stub = new Student();
//将实体参数直接复制给b,并传递
stub = stua;
ageAdd(stub);
System.out.println("==================");
System.out.println("stua---->"+stua);
}
public static void ageAdd(Student stub) throws CloneNotSupportedException {
stub.setAge(stub.getAge()+1);
System.out.println("stub---->"+stub);
}
}
3.得出结果,改变了实参的属性值
解决方法:只需要在实体类实现Cloneable接口,并且重写clone方法
实体类变为:
public class Student implements Cloneable {
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
'}';
}
/**
* 记得重写克隆方法
* @return
* @throws CloneNotSupportedException
*/
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
测试类为:
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Student stua = new Student("zhangsan",15);
System.out.println("stua---->"+stua);
Student stub = new Student();
//将实体参数的值克隆一份并传递
stub = (Student) stua.clone();
ageAdd(stub);
System.out.println("==================");
System.out.println("stua---->"+stua);
}
public static void ageAdd(Student stub) throws CloneNotSupportedException {
stub.setAge(stub.getAge()+1);
System.out.println("stub---->"+stub);
}
}
测试结果:
**
最后有个疑问:java不是不涉及引用传递吗?这里为什么会改变原来对象的值呢?
**
最后
以上就是闪闪路人为你收集整理的实体作为参数传递,到底是值传递还是引用传递的全部内容,希望文章能够帮你解决实体作为参数传递,到底是值传递还是引用传递所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复