前言:我们经常会看到一个方法中里面不带参数,反而带类的情况。但是参数比较好理解,但是类可能会有点晕。所以这个例子解释了下带类的作用
1
| public void method(Student s);
|
案例:
形式参数如果是一个基本数据类型,形参的改变对实参数没有影响,需要什么数据,传递具体的值即可,形式参数如果是一个类(具体类),那么形式参数的改变直接影响实际参数!
结论:
形式参数如果传递的是一个数组类型,需要传递的该数组的对象
形式参数如果传递的是具体的类,需要传递该类的具体对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| class Demo{ public int add(int a,int b){ return a+b; } }
class Student{ public void study(){ System.out.println("Good study"); } }
class StudentMethod{ public void method(Student s){ s.study(); } }
class ArgsDemo1{ public static void main(String[] args){ Demo d=new Demo(); int result=d.add(10,20); System.out.println("结果是:"+result); StudentMethod sm=new StudentMethod(); Student y=new Student(); sm.method(y);
} }
结果是:30 Good study
|