1. When developing the system, the main structure uses the interface and the interface forms the skeleton of the system.
2. This allows the system to be replaced by replacing the implementation class of the interface.
public class Printerdemo{public static void Main (string[] args) {colorprinter CP = new Colorprinter ("HP"); Blackprinter bp = new Blackprinter ("Lenovo"); Teacher Teacher = new Teacher ("Zhang San", 26); School School = new School (), School.setprinter (CP), School.setprinter (BP), School.print (School); School.print (teacher ); Bp.print ("abc"); Cp.print ("abc");}} Class School implements Iinfo{private Printer p = null;public void SetPrinter (Printer p) {this.p = P;} public void print (Iinfo info) {p.print (Info.detail ());} Public String Detail () {return "I am a school";}} Interface iinfo{//interface, teachers and schools have the method string detail ();} Abstract class Printer{private string Brand;public string Getbrand () {return brand;} Public Printer (String brand) {//constructor method This.brand = brand;} public abstract void Print (String content); Class Colorprinter extends Printer{public colorprinter (String brand) {super (brand);} public void print (String content) {System.out.println (Getbrand () + "COLOR print:" +content);}} Class Blackprinter extends Printer{public blackprinter (String Brand) {super (brand);} public void print (String content) {System.out.println (Getbrand () + "black-and-white printing:" +content);}} Class Teacher implements iinfo{private string name;private int age;public Teacher (String name,int age) {this.name = Name;t His.age = age;} Public String Detail () {return "My name is" +name+ ", Age is" +age;}}
Java Interface Instance