interface is mainly used to implement multiple inheritance, it is a collection of constants and methods, these methods only declarations are not implemented, that is, the interface itself is abstract, the system by default with the abstract decoration.
1. Definition of the interface:
1 Public Interface a{2 int A=1; // default is public static final constant 3 void Displaya (); // default is public abstract abstract method 4 }
2. Interfaces can implement multiple inheritance:
1 Interfacea{2 intA=1;3 voidDisplaya ();4 }5 Interfaceb{6 intb=2;7 voidDisplayb ();8 }9 interface C extendsA, b{Ten intC=3; One voiddisplayc (); A } -class ABC implements C - { the Public voidDisplaya () - { - System.out.println (A); - } + Public voidDisplayb () - { + System.out.println (B); A } at Public voiddisplayc () - { - System.out.println (C); - } - } - Public classT04 in { - Public Static voidMain (string[] args) to { +ABC A =NewABC (); -ABC B =NewABC (); theABC C =NewABC (); * A.displaya (); $ B.displayb ();Panax Notoginseng c.displayc (); - } the}
in the example above, the interface C multiple inherits interfaces a and B, and class ABC implements the interface by implementing interface C. the method in a and B , which is a manifestation of multiple inheritance.
3. The difference between an interface and an abstract class:
There are only abstract methods in the interface, there is no ordinary method, and the interface is not constructed.
interfaces cannot be inherited and can only be implemented.
above: Public class ABC implements c{} is the method by which the class implements the interface.
4. Constants defined in the interface can be accessed directly with the class name.
System.out.println (ABC. A);
5.GUI Program Event Handling-an example of interface use.
1 Importjava.awt.FlowLayout;2 Importjava.awt.event.*;3 Importjavax.swing.*;4 5 Public classEventdemoextendsJFrameimplements ActionListener6 { 7JButton button1 =NewJButton ("Login");8JButton button2 =NewJButton ("Cancel");9JTextField JTF =NewJTextField (20);Ten PublicEventdemo () One { A Add (JTF); - Add (button1); - Add (button2); the Button1.addactionlistener (this);//registering event listeners for a button - Button2.addactionlistener (this); -SetSize (600,350); -SetVisible (true); +SetLayout (NewFlowLayout ()); - setdefaultcloseoperation (jframe.exit_on_close); + } A Public void actionperformed (ActionEvent e)//implementing an abstract method in an interface at { - if((JButton) e.getsource () = =button1) -Jtf.settext ("* * *"); - Else -Jtf.settext ("&&&"); - } in Public Static voidMain (string[] args) - { toEventdemo frame =NewEventdemo (); + } -}
Make up for Java single inheritance--interface