Java中接口作为方法的 参数和返回值

思想:可以返回接口,接口虽然不能被实例化,但是接口的实现类都可以向上转型为接口。
所谓面向接口编程是指我们在编写代码时对数据参数的定义尽量写成接口,待真正实现的时候再用实际类型代替。
好处:代码的耦合性降低,在运行时我只需修改实现类类型,就可以实现不同的功能,而不必要修改接口的代码。表面上是返回的接口,其实返回的是接口的实现类。

一、接口作为方法的参数进行传递:必须传递进去一个接口的实现类对象。(跟接口一样)

例:

//抽烟接口
public interface Smoking{
       void smoking();
}
//学生类
public class Student implements Smoking {
    public void smoking() {
        System.out.println("Students are not allowed to smoke!");
    }
}
//测试类
public class Test{
    public static void main(String[] args) {
        Student s = new Student(); //改成多态调用:Smoking s = new Student();        
        smoking(s); //打印结果:Students are not allowed to smoke!
    }
 
    public static void smoking(Smoking s) { //接口作为参数。
        s.smoking();
    }
}

二、接口作为方法的返回值进行传递:必须返回一个接口的实现类的对象。

例:

//抽烟接口
public interface Smoking{
       void smoking();
}
 

//学生类
public class Student implements Smoking {
    public void smoking() {
        System.out.println("Students are not allowed to smoke!");
    }
}
//测试类
public class Test {
    public static void main(String[] args) {
        Smoking s = smoking(); //相当于Smoking s  = new Student();
        s.smoking(); //打印结果:Students are not allowed to smoke!
    }
 
    public static Smoking smoking() {
        return new Student();//返回接口实现类的对象。
    }
}

你可能感兴趣的:(Java,java,接口)