形式参数之是类,是抽象类,还是接口?
基本类型
引用类型
类: 需要的是该类的对象
抽象类:需要的是该类的子类对象。
接口:需要的是该接口的实现类对象
//形式参数为具体类时
package Practice
class Student{
public void study() {
System.out.println("好好学习");
}
}
class StudentDemo{
public void method(Student s) {
System.out.println("天天向上");
}
}
public class StudentTest {
public static void main(String[] args) {
//需求:调用StudentDemo中的method方法
StudentDemo sd = new StudentDemo();
Student s = new Student();
sd.method(s);
//new.StudentDemo().method(new.Student());
}
}
//当形式参数为一个抽象类时
package Practie;
abstract class Person{
abstract public void study();
}
class PersonDemo{
public void method(Person p) {
p.study();
}
}
class Teacher extends Person{
public void study() {
System.out.println("好好学习");
}
}
public class PersonTest {
public static void main(String[] args) {
PersonDemo pd = new PersonDemo();
Person p = new Teacher();
pd.method(p);
}
}
//当形式参数为接口时
package Practie;
interface Person{
abstract public void study();
}
class PersonDemo{
public void method(Person p) {
p.study();
}
}
class Teacher implements Person{
public void study() {
System.out.println("好好学习");
}
}
public class PersonTest {
public static void main(String[] args) {
PersonDemo pd = new PersonDemo();
Person p = new Teacher();
pd.method(p);
}
}