package com.imooc; class Student{ public void study(){ System.out.println("学生学习"); } } class StudentDemo{ public Student getStudent(){ return new Student(); } } public class ReturnDemo { public static void main(String[] args){ StudentDemo sd = new StudentDemo(); Student s = sd.getStudent(); s.study(); } }
抽象类作为返回值类型,返回的是该抽象类的子类对象
package com.imooc; abstract class Person{ public abstract void study(); } class Student extends Person{ public void study(){ System.out.println("学生爱学习"); } } class StudentDemo{ public Person getPerson(){ return new Student(); } } public class ReturnDemo { public static void main(String[] args){ StudentDemo sd = new StudentDemo(); Person p = sd.getPerson(); p.study(); } }
接口作为返回返回值类型,返回的是实现该接口的实现类的对象
package com.imooc; interface Love{ public abstract void love(); } class Teacher implements Love{ public void love(){ System.out.println("老师爱上课"); } } class TeacherDemo{ public Love getLove(){ return new Teacher(); //因为teacher实现了Love接口 } } public class TeacherTest { public static void main(String[] args){ TeacherDemo td = new TeacherDemo(); Love l = td.getLove(); l.love(); } }
如果每次调用完方法都返回一个对象,那么便可以实现链式编程
例如:
package com.imooc; interface Love{ public abstract void love(); } class Teacher implements Love{ public void love(){ System.out.println("老师爱上课"); } } class TeacherDemo{ public Love getLove(){ return new Teacher(); //因为teacher实现了Love接口 } } public class TeacherTest { public static void main(String[] args){ TeacherDemo td = new TeacherDemo(); Love l = td.getLove(); l.love(); //链式编程:每次调用完方法之后返回的是一个对象 td.getLove().love(); //td是一个对象,td.getLovce()返回的是一个实现Love接口的对象, //可以再调用这个对象的方法 } }