The role of interfaces: 1. Interfaces can separate projects, and all layers are developed towards interfaces, improving development efficiency; 2. Interfaces reduce the coupling between code and code; 3. Interfaces can be implemented in multiple ways, Multiple inheritance, and in addition to interfaces, a class can also inherit other classes.
The role of the interface:
(Recommended tutorial: java entry program)
1. Projects can be separated, and all layers are developed for interfaces to improve development efficiency;
2. The interface reduces the coupling between code and code, becomes pluggable, and can be switched at will;
3. Both interfaces and abstract classes can complete a certain function. Interfaces are preferred because interfaces can be implemented and inherited in multiple ways, and in addition to interfaces, a class can also inherit other classes.
(Video tutorial recommendation: java video tutorial)
Code sample:
public interface CustomerService { //定义一个推出系统的方法 void logout(); } package date818;//接口实现类1public class CustomerServierImpl implements CustomerService { public void logout(){ System.out.println("成功退出系统"); } } package date818;//接口实现类2public class CustomerServiceImpl2 implements CustomerService{ public void logout(){ System.out.println("hello world"); } } package date818;public class TestCustomer { public static void main(String[] args){ //需要执行CustomerServiceImpl和CustomerImpl2接口实现类中的logout方法 //以下程序面向接口调用 CustomerService cs = new CustomerServierImpl();//多态。父类型引用指向子类型对象 //调用 cs.logout(); CustomerService cs2 = new CustomerServiceImpl2(); cs2.logout(); } }
Define interface
package date818; public interface Engine { //所有发动机都可以通过这个接口启动 void start(); }//定义实现接口的类 package date818; public class Honda implements Engine{ public void start(){ System.out.println("本田启动"); } } package date818;public class Ymaha implements Engine{ public void start(){ System.out.println("雅马哈启动"); } }//定义生产汽车的类package date818;public class Car { //面向接口编程,不能将类实例化 /** * 引用接口定义一个属性e,相当于 * String name; * Integer age; * 类里定义的变量是成员变量;方法里定义的变量是局部变量。 */ Engine e ;//成员变量e Car(Engine e){ //定义构造方法,把局部变量e赋值给成员变量 this.e=e; } //对外提供的测试方法 public void testEngine(){ //成员变量e e.start(); } }//定义测试类package date818;public class TestCar { public static void main(String[] args){ //生产引擎 Engine e = new Ymaha(); //根据构造方法传入参数生产汽车 Car c = new Car(e); //测试引擎 c.testEngine(); c.e = new Honda();//已经定义了一个实例,直接对实例的参数修改即可 c.testEngine(); } }
The above is the detailed content of What does the interface do?. For more information, please follow other related articles on the PHP Chinese website!