classStudentTest{ publicstaticvoidmain(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()); } }
classTeacherTest{ publicstaticvoidmain(String[] args){ LoveDemo ld = new LoveDemo(); Love l = new Teacher(); ld.method(l); } }
返回值
类做返回值
问
使用StudentDemo创建对象,在测试类中使用study()方法
classStudent{ publicvoidstudy(){ System.out.println("Good Good Study,Day Day Up"); } }
classStudentDemo{ public Student getStudent(){ } }
答
classStudentDemo{ public Student getStudent(){ returnnew Student(); } }
classStudentTest{ publicstaticvoidmain(String[] args){ StudentDemo sd = new StudentDemo(); Student s = sd.getStudent(); s.study(); // 链式编程 sd.getStudent().study(); } }
抽象类做返回值
问
测试Person类中的study()方法
abstractclassPerson{ publicabstractvoidstudy(); }
classPersonDemo{ public Person getPerson(){ } }
答
classPersonDemo{ public Person getPerson(){ // Person p = new Student(); 反抽象类的子类 returnnew Student(); } } // 创建一个具体类继承抽象类,重写study()方法 classStudentextendsPerson{ publicvoidstudy(){ System.out.println("Good Good Study,Day Day Up"); } }
classPersonTest{ publicstaticvoidmain(String[] args){ PersonDemo pd = new PersonDemo(); Person p = pd.getPerson(); p.study(); } }