- 类名作为形式参数:
//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;
}
}