Java中接⼝作为⽅法的参数和返回值
思想:可以返回接⼝,接⼝虽然不能被实例化,但是接⼝的实现类都可以向上转型为接⼝。
所谓⾯向接⼝编程是指我们在编写代码时对数据参数的定义尽量写成接⼝,待真正实现的时候再⽤实际类型代替。
好处:代码的耦合性降低,在运⾏时我只需修改实现类类型,就可以实现不同的功能,⽽不必要修改接⼝的代码。表⾯上是返回的接⼝,其实返回的是接⼝的实现类。
⼀、接⼝作为⽅法的参数进⾏传递:必须传递进去⼀个接⼝的实现类对象。(跟接⼝⼀样)
例:
//抽烟接⼝
public interface Smoking{
void smoking();
}
//学⽣类
public class Student implements Smoking {
public void smoking() {
System.out.println("Students are not allowed to smoke!");s parameter
}
}
//测试类
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();//返回接⼝实现类的对象。
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论