类名分别作为形式参数和返回值类型

这里写图片描述
- 类名作为形式参数:

//Test类
package com.zws07;

/*
 *
 * 调用teacher的test方法
 * 类名作为形式参数,需要的其实是该类的对象
 */
public class Test {
    public static void main(String[] args) {
        //调用teacher类的方法,先创建一个teacher对象
        Teacher t = new Teacher();
        //teacher类中形式参数是Student s,所以创建一个Student对象
        Student s = new Student();
        t.test(s);
    }

}
// Student类
package com.zws07;

public class Student {
    public void study() {
        System.out.println("好好学习,天天向上");
    }
}
//Teacher类
package com.zws07;

public class Teacher {
    //类名作为形式参数,需要的其实是该类的对象,如下:
    public void test(Student s) {
        s.study();
    }

}

  • 类名作为返回值类型:
//Test类:
package com.zws08;
/*
 * 需求:通过Teacher得到Student对象,然后调用Student类的方法
 * 如果方法的返回值是类名,其实返回的是该类的对象
 */
public class Test {
    public static void main(String[] args) {
        //创建一个Teacher对象
        Teacher ter = new Teacher();
        //通过对象ter调用Teacher中的getStudent方法得到Student对象
        Student stu = ter.getStudent();
        stu.study();
    }
}
//Student类
package com.zws08;


public class Student {
    public void study() {
        System.out.println("好好学习,天天向上");
    }
}
//Teacher类
package com.zws08;

public class Teacher {
    // 如果方法的返回值是类名,其实返回的是该类的对象,如下:
    public Student getStudent() {
        Student s = new Student();
        return s;
    }
}
  • 16
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值