您的位置:首页 > 其它

面向对象-方法参数传递

2017-11-23 19:48 183 查看

Java程序在执行过程中,参数的传递:

1、传递的数据为基本数据类型;

2、传递的数据为引用数据类型。

基本数据类型:

public class OOTest {
public static void main(String[] args) {
Integer integer=new Integer(10);
addInteger(integer);
System.out.println(integer);
}

private static void addInteger(Integer integer) {
// TODO Auto-generated method stub
integer++;
System.out.println(integer);
}
}
输出结果为:11  10

integer为成员变量,作用域只限在方法内。所以当执行完成addInteger方法后,main方法内的integer与addInteger里的integer对应在不同的内存中,

所以main内的integer参数仍为10。

引用数据类型:

当传递的数据类型为引用数据类型时,会有不同,从下面代码中,可以注意到:

public class OOTestAnimal {
public static void main(String[] args) {
Animal animal=new Animal(10);
m1(animal);
System.out.println("main age="+animal.age);
}

private static void m1(Animal animal) {
// TODO Auto-generated method stub
animal.age++;
System.out.println("m1 age="+animal.age);
}
}
class Animal{
int age;
Animal(int _age){
age=_age;
}
}
输出为:

testPassObject age=11

main age=11

我们注意到输出结果均为11,虽然testPassObject内的animal对象和main方法中的animal对象内存不同,但保存的内存地址相同,所以指向的是堆中

的同一对象,所以输出结果相同;传递引用数据类型,实际上传的为内存地址。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐