这个方法为什么没有引用地址

qq_41232595 2018-05-01 07:45:36
public class Student {//定义的类
public Student(String name) {
this.name=name;
}
public Student(String name,int scores) {
this.name=name;
this.scores=scores;
}
String name =new String();
double scores;
}
public static void main(String[]args) {
Student a=new Student("a",12);
Student b=new Student("b",34);
Student temp=new Student("temp",0);
work1.exchangeClass(a, b);
System.out.println("...");
}
public static void exchangeClass(Student a,Student b) {//交换方法
Student temp=new Student("temp");
temp=a;
a=b;
b=temp;
}
调试发现 在方法内部 类确实发生了交换 外部没有变化 也就是说方法不是引用 , 怎么办?
...全文
857 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
gshywx 2018-05-04
  • 打赏
  • 举报
回复
没有上机跑,看起来很典型
阿顾同学 2018-05-03
  • 打赏
  • 举报
回复
你可以写一个方法,方法的返回值Student 数组,交换之后,然后给返回出去,这样外面才有对应的引用地址
天行归来 2018-05-03
  • 打赏
  • 举报
回复

package com.lms;

public class Student {//定义的类
	String name;
	double scores;

	public Student(String name) {
		this.name=name;
	}
	public Student(String name,double scores) {
		this.name=name;
		this.scores=scores;
	}

	public static  void exchangeClass(Student a,Student b) {
		Student temp= new Student(a.name,a.scores);
		
		a.name = b.name;
		a.scores = b.scores;
		
		b.name = temp.name;
		b.scores = temp.scores;
	}
	public static void main(String[]args) {
		Student a=new Student("a",12);
		Student b=new Student("b",34);
		Student.exchangeClass(a, b);
		System.out.println("student "+a.name+"'s score:"+a.scores);
		System.out.println("student "+b.name+"'s score:"+b.scores);
	}
}
oyljerry 2018-05-02
  • 打赏
  • 举报
回复
参数是引用的拷贝,你通过temp等来交换,出了函数就变成原来的引用了。 你这个应该函数内部来交换a,b的成员的数据。
Cain Yang 2018-05-02
  • 打赏
  • 举报
回复
java是按引用传值,实际上传递的是引用的拷贝,你在方法里面修改引用的地址,对方法外面的引用没有任何影响。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧