一、什么是引用类型
在Java中引用类型包括三种:类、抽象类、接口。
二、引用类型作为形参使用
1、类作为形参
/** * 类作为形参,实际传递的是该类的对象 */ class Student { public void study() { System.out.println("Good Good Study, Day Day Up"); } } class StudentDemo { public void show(Student s) { s.study(); } } public class StudentTest { public static void main(String[] args) { StudentDemo sd = new StudentDemo(); Student s = new Student(); sd.show(s); } }
2、抽象类作为形参
/** * 抽象类作为形参,传递的是实现该抽象类的子类对象 */ abstract class Person { public abstract void eat(); } class XiaoMing extends Person { @Override public void eat() { // TODO Auto-generated method stub System.out.println("小明爱吃米饭"); } } class PersonDemo { public void show(Person p) { p.eat(); } } public class PersonTest { public static void main(String[] args) { PersonDemo pd = new PersonDemo(); // 方式一、传递的是实现该抽象类的子类对象 Person p = new XiaoMing(); // 多态 pd.show(p); System.out.println("------------------"); // 方式二、直接实现抽象类,传递匿名子类对象 pd.show(new Person() { @Override public void eat() { // TODO Auto-generated method stub System.out.println("小明爱上了吃面条"); } }); } }