00058_类作为方法参数与返回值
1、类作为方法参数
在编写程序中,会经常碰到调用的方法要接收的是一个类类型的情况,那么这时,要向方法中传入该类的对象。
1 class Person{ 2 public void show(){ 3 System.out.println("show方法执行了"); 4 } 5 } 6 //测试类 7 public class Test { 8 public static void main(String[] args) { 9 //创建Person对象 10 Person p = new Person(); 11 //调用method方法 12 method(p); 13 } 14 15 //定义一个方法method,用来接收一个Person对象,在方法中调用Person对象的show方法 16 public static void method(Person p){ 17 p.show(); 18 } 19 }
2、类作为返回值
写程序调用方法时,我们以后会经常碰到返回一个类类型的返回值,那么这时,该方法要返回一个该类的对象。
1 class Person{ 2 public void show(){ 3 System.out.println("show方法执行了"); 4 } 5 } 6 //测试类 7 public class Test { 8 public static void main(String[] args) { 9 //调用method方法,获取返回的Person对象 10 Person p = method(); 11 //调用p对象中的show方法 12 p.show(); 13 } 14 15 //定义一个方法method,用来获取一个Person对象,在方法中完成Person对象的创建 16 public static Person method(){ 17 Person p = new Person(); 18 return p; 19 } 20 }

浙公网安备 33010602011771号