方法的形参的传递机制:值传递
1.形参:方法定义时,声明的小括号内的参数
实参:方法调用时,实际传递给形参的数据
2.值传递机制
如果参数是基本数据类型,此时实参赋给形参的是实参真实存储的数据值。
如果参数是引用数据类型,此时实参赋给形参的是实参存储数据的地址值。
例题
/*public class Test080600{
public static void main(String[] args){
Test080600 test = new Test080600();
int m = 10;
int n = 20;
System.out.println("m = " + m +",n = " + n);//m = 10,n = 20;
test.swap(m,n);
System.out.println("m = " + m +",n = " + n);//m = 10,n = 20;
}
public void swap(int m,int n){
int temp = m;
m = n;
n = temp;
}
}
*/
public class Test080601{
public static void main(String[] args){
Data data = new Data();
data.m = 10;
data.n = 20;
System.out.println("m = " + data.m +",n = " + data.n);//m = 10,n = 20;
Test080601 test = new Test080601();
test.swap(data);
System.out.println("m = " + data.m +",n = " + data.n);//m = 20,n = 10;
}
public void swap(Data data){
int temp = data.m;
data.m = data.n;
data.n = temp;
}
}
class Data{
int m;
int n;
}
public class CircleTest0806{
public static void main(String[] args){
Circle c = new Circle();
c.radius = 10.6;
CircleTest0806 test = new CircleTest0806();
test.findArea(c);
}
public void findArea(Circle c){
double area = Math.PI * c.radius * c.radius;
System.out.println("面积为:" + area);
}
}
class Circle{
double radius;
}
/*public class CircleTest1{
public static void main(String[] args){
Circle c = new Circle();
c.r = 3.4;
c.findArea();
}
}
*/
public class Circle0806{
double r;//属性
public double findArea(){//方法
return Math.PI * r * r;
}
}
public class PassObject{
public static void main(String[] args){
PassObject test = new PassObject();
Circle0806 c = new Circle0806();
test.printAreas(c,6);//c可以直接用new Circle0806()代替(匿名对象)
System.out.println("now r is" + c.r);
}
public void printAreas(Circle0806 c,int time){
System.out.println("r\t\tfindArea");
int i = 1;
for(;i <= time;i++){
c.r = i;
System.out.println("面积为:" + c.findArea());
}
//c.r = time++;
c.r = i;
}
}
3.递归方法(了解)
定义:一个方法体内调用它自身。
理解:方法递归包含了一种隐式的循环,他会重复执行某段代码,但这种重复执行无需循环控制。
递归一定要向已知方向递归,否则就会变成一个无穷递归,类似于死循环。
例题:
public class RecursionTest{//计算1~100所有自然数的和
public static void main(String[] args){
RecursionTest test = new RecursionTest();
int sum = test.getSum(100);
System.out.println(sum);
int value = test.f(10);
System.out.println(sum);
}
public int getSum(int n){
if(n == 1){
return 1;
}
else {
return n + getSum(n-1);
}
}
//已知有一个数列:f(0)=1,f(1)=4,f(n+2)=2*f(n+1)+f(n),n为大于零的整数,求f(10).
public int f(int n){
if(n == 0){
return 1;
}
else if(n == 1){
return 4;
}
else{
return 2*f(n-1) + f(n-2);
}
}
//斐波那契数列:1,1,2,3,5,8,13,21,34,55
//一个数等于前2个数的和
//还有汉诺塔、快排等。
}