java 参数传值
基本数据类型参数的传值,参数为基本数据类型
class Computer{ int add(int x,int y){ return x+y; } } public class Example4_6 { public static void main(String args[]){ Computer com = new Computer(); int m = 100; int n = 200; int result = com.add(m,n); System.out.println(result); } }
引用类型参数传值,参数为一个类
Battery.java
public class Battery { int electricityAmount; Battery(int amount){ electricityAmount = amount; } }
Example4_7.java
public class Example4_7 { public static void main(String args[]) { Battery nanfu = new Battery(100); System.out.println("南孚电池的储电量是:"+nanfu.electricityAmount); Radio radio = new Radio(); System.out.println("收音机开始使用南孚电池"); radio.openRadio(nanfu); System.out.println("目前南孚电池的储电量是:"+nanfu.electricityAmount); } }
Radio.java
public class Radio { void openRadio(Battery battery){ battery.electricityAmount = battery.electricityAmount - 10; } }