面向对象-方法参数传递

来源:互联网 发布:网络水军是什么 编辑:程序博客网 时间:2024/05/18 22:42

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 stubinteger++;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 stubanimal.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对象内存不同,但保存的内存地址相同,所以指向的是堆中

的同一对象,所以输出结果相同;传递引用数据类型,实际上传的为内存地址。