每日一学(13)——(面向对象)类作为方法参数与返回值

类作为方法参数

在编写程序中,会经常碰到调用的方法要接收的是一个类类型的情况,那么这时,要向方法中传入该类的对象。如下代码演示:

package day14;

public class Person {
   private String name="张三";
   public void eat(){
       System.out.println(name+"在吃饭");
   }
   public void run(){
       System.out.println(name+"在跑步");
   }
}

package day14;

public class TestArguments {
  /*
   * Person的测试类,Person当作方法的参数
   * Person类写在参数的列表中
   */
    public static void main(String[] args) {
        //调用方法operatorPerson,传递Person类型对象
        Person p=new Person();//p是实际参数
        operatorPerson(p);//有名对象
        operatorPerson(new Person());//匿名对象,但是只能使用一次哦
    }
        /*
         * 方法operatorPerson,参数类型是Person类型
         * 调用方法operatorPerson,必须传递Person类型的对象
         */
        public static void operatorPerson(Person p){//p是形式参数
            //可以使用引用类型p调用Person类的功能
            p.eat();
            p.run();    
    }
}

类作为方法返回值 

写程序调用方法时,我们以后会经常碰到返回一个类类型的返回值,那么这时,该方法要返回一个该类的对象。如下代码演示:

package day14;
/*
 * 定义类方法返回Person类型 
 */
public class GetPerson {
    /*
     * 方法返回值是Person类型 
     * 方法的return语句后面一定是Person类型的对象
     */
  public Person get(){
      Person p=new Person();
      return p;
  }
}

 package day14;
/*
 * 通过get方法获取到了Person类的对象
 * Person对象的创建是在get方法中完成的
 */
public class TestReturn {
    public static void main(String[] args) {
        //调用GetPerson类中的get
        //用get返回Person类型
        GetPerson g=new GetPerson();
        Person p=g.get();
        p.eat();
        p.run();
        //另外一种方法,eat后面是空
        new GetPerson().get().eat();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42517286/article/details/81286697