13.4 类作为方法参数与返回值

类作为方法的参数:

class Person{

    public voidshow(){

        System.out.println("show方法执行了");

    }

}

//测试类

public class Test {

    public staticvoid main(String[] args) {

        //创建Person对象

        Person p= new Person();

        //调用method方法

        method(p);

    }

    //定义一个方法method,用来接收一个Person对象,在方法中调用Person对象的show方法

    public static void method(Person p){

        p.show();

    }

}


类作为方法的返回值:

class Person{

    public voidshow(){

        System.out.println("show方法执行了");

    }

}

//测试类

public class Test {

    public staticvoid main(String[] args) {

        //调用method方法,获取返回的Person对象

        Person p= method();

        //调用p对象中的show方法

        p.show();

    }

    //定义一个方法method,用来获取一个Person对象,在方法中完成Person对象的创建

    public static Person method(){

        Person p= new Person();

        return p;

    }

}


猜你喜欢

转载自blog.csdn.net/southdreams/article/details/80168922