形式参数
自定义函数中的“形参”全称为"形式参数" 由于它不是实际存在变量,所以又称虚拟变量。实参和形参可以重名。
类做形式参数
问
-
测试
Student
类的study()
方法 -
测试
StudentDemo
类中的method()
方法
class Student {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class StudentDemo {
public void method(Student s) {
s.study();
}
}
答
class StudentTest {
public static void main(String[] args) {
//需求1
Student s = new Student();
s.study();
System.out.println("----------------");
//需求2
StudentDemo sd = new StudentDemo();
Student ss = new Student();
sd.method(ss);
System.out.println("----------------");
//匿名对象用法
new StudentDemo().method(new Student());
}
}
抽象类做形参
问
使用PersonDemo
类中的method()
方法
abstract class Person {
public abstract void study();
}
class PersonDemo {
public void method(Person p) {
p.study();
}
}
答
//定义一个具体的学生类
class Student extends Person {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class PersonTest {
public static void main(String[] args) {
// 直接使用是不行的,因为抽象类没有对应的具体类
// 因此定于一个具体的类
PersonDemo pd = new PersonDemo();
Person p = new Student();
// 使用具体类调用method()
pd.method(p);
}
}
接口做形参
问
测试LoveDemo
类中的love()
方法
//定义一个爱好的接口
interface Love {
public abstract void love();
}
class LoveDemo {
public void method(Love l) {
l.love();
}
}
答
//定义具体类实现接口
class Teacher implements Love {
public void love() {
System.out.println("极限挑战,这就是爱");
}
}
class TeacherTest {
public static void main(String[] args) {
LoveDemo ld = new LoveDemo();
Love l = new Teacher();
ld.method(l);
}
}
返回值
类做返回值
问
使用StudentDemo
创建对象,在测试类中使用study()
方法
class Student {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class StudentDemo {
public Student getStudent() {
}
}
答
class StudentDemo {
public Student getStudent() {
return new Student();
}
}
class StudentTest {
public static void main(String[] args) {
StudentDemo sd = new StudentDemo();
Student s = sd.getStudent();
s.study();
// 链式编程
sd.getStudent().study();
}
}
抽象类做返回值
问
测试Person
类中的study()
方法
abstract class Person {
public abstract void study();
}
class PersonDemo {
public Person getPerson() {
}
}
答
class PersonDemo {
public Person getPerson() {
// Person p = new Student(); 反抽象类的子类
return new Student();
}
}
// 创建一个具体类继承抽象类,重写study()方法
class Student extends Person {
public void study() {
System.out.println("Good Good Study,Day Day Up");
}
}
class PersonTest {
public static void main(String[] args) {
PersonDemo pd = new PersonDemo();
Person p = pd.getPerson();
p.study();
}
}
接口做返回值
问
//定义一个爱好的接口
interface Love {
public abstract void love();
}
class LoveDemo {
public Love getLove() {
}
}
答
class LoveDemo {
public Love getLove() {
//Love l = new Teacher();反回具体类对象
return new Teacher();
}
}
//定义具体类实现接口
class Teacher implements Love {
// 重写Love()方法
public void love() {
System.out.println("极限挑战,这就是爱");
}
}
class TeacherTest {
public static void main(String[] args) {
//测试
LoveDemo ld = new LoveDemo();
Love l = ld.getLove();
l.love();
}
}