看不懂

sweetswing 2019-08-12 01:15:31
what is the output of this code?
class A{
int x=1;
}
class B{
static A a1=new A();
static A a2=new A();
static void m(A a){
a.x+=2;
}
public static void main(String[] args){
m(a1);m(a2);
System.out.println(a1.x+a2.x);
}
}


答案是6

static A a1=new A();
static A a2=new A();
static void m(A a){
a.x+=2;
}
public static void main(String[] args){
m(a1);m(a2);

这段什么意思嘛?
...全文
96 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
guishuanglin 2019-08-12
  • 打赏
  • 举报
回复
楼上说的是对的, 你可以用调试模式一行看变量结果.
qq_39936465 2019-08-12
  • 打赏
  • 举报
回复
引用 楼主 sweetswing 的回复:
static A a1=new A(); static A a2=new A(); static void m(A a){ a.x+=2; } public static void main(String[] args){ m(a1);m(a2); 这段什么意思嘛?
就是class B 静态实例化了2个A类,一个a1,一个a2; 然后调用静态方法m,m方法的参数为A类的实例; 也就是分别执行了 a1.x+=2; a2.x+=2; 因为x初始值为1,所以a1.x=3,a2.x=3

62,615

社区成员

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

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