Java programming ideology interface (implement multi-inheritance in Java ?!)

Source: Internet
Author: User

1. interface is not just an extremely abstract class, because it allows people to create a class that can be transformed up to multiple base types to implement a class similar to C ++Multiple inheritance variants.

2. Like a class, you can add a public keyword before the interface keyword (but only for this interfaceSame nameIs defined in the file), or does not add it to make it only havePackage access permissionIn this way, it can only be available in the same package.

3. You can declare the methodPublicBut even if you do not, they are also public. Therefore, when an interface is implemented, the method defined in the interfaceMust be defined as public.

4. in Java, the access permissions of methods cannot be reduced.

5. The interface can also contain fields, but they are implicitlyStatic and final.

6. Because the interface has no specific implementation at all -- that is, there is no storage related to the interface; therefore, the combination of multiple interfaces cannot be blocked, that is,"Multi-Inheritance". Example:

Interface canfight {void fight ();} interface canswim {void swim ();} interface canfly {void fly ();} class actioncharacter {public void fight () {system. out. println ("actioncharacter. fight () ") ;}} class hero extends actioncharacter implements canfight, canswim, canfly {public void swim () {system. out. println ("Hero. swim () ");} public void fly () {system. out. println ("Hero. fly () ");}/** 1. note the fight () method in canfight and Not defined here * 2. This is because the canfight interface and the fight () method in the actioncharacter class have the same feature signature. * 3. Therefore, even if hero does not explicitly provide the fight () definition, its definition also comes with actioncharacter. * 4. If you change fight () of actioncharacter to private, an error will be prompted that * "type hero must implement the inherited abstract method canfight. Fight. * 5. If you change fight () of actioncharacter to private, an error will be prompted that * "the inherited method actioncharacter. Fight () cannot hide the common abstract methods in canfight. */} Public class adventure {public static void T (canfight X) {X. fight ();} public static void U (canswim X) {X. swim ();} public static void V (canfly X) {X. fly ();} public static void W (actioncharacter X) {X. fight ();} public static void main (string [] ARGs) {hero H = new hero (); t (h); U (h); V (h ); W (h );}}

Running result:

1). Pay attention toFight () methodNot Defined in hero

2). This is because the canfight interface and the fight () method in the actioncharacter class have the same feature signature.

3). Therefore, even if hero does not explicitly provide the definition of fight (), its definition also comes with actioncharacter.

4). If you change the actioncharacter fight ()PrivateThe error message "type hero must implement the inherited abstract method canfight. Fight ()" appears.

5). If you change the actioncharacter fight ()PrivateThe error message "the inherited method actioncharacter. Fight () cannot hide the public abstract method in canfight" appears.

7. The above example shows the core reasons for using interfaces:To be able to transform to multiple base types.

8. The second reason for using an interface: it is the same as using an abstract base class to prevent client programmers from creating objects of this class and ensure that this is only an interface.

9. interface or abstract class should be used: When you want to create a base class without any method definition or member variables, use the interface.

10. In fact, if you know that something should be a base classThe first choice should be to make it an interface,You must select an abstract class or make it a specific class only when required to have a method definition and a member variable.

11. interfaces are extended through inheritance, as shown below:

interface Plant{   void grow();}interface Flower extends Plant{   void bloom();}interface Apple extends  Plant, Flower{   void fruit();}class RedApple implements Apple{   public void grow(){      System.out.println("RedApple isgrowing.");   }   public void bloom(){      System.out.println("RedApple isblooming.");   }   public void fruit() {      System.out.println("RedApple isfruiting.");   }}

After you can see the apple interfaceExtends plant, flower. Generally, extends can be used only for a single class. However, since an interface can be generated by multiple other interfacesWhen creating a new interface, extends can certainly reference multiple basic class interfaces..This syntax applies only to inheritance of interfaces.

12. Building in Java is as type-safe as the enum type of C ++(The value of a variable is limited to a limited range ):

Public final class month {private string name; // private constructor, unable to create any of its instances, all instances have their own finalstatic instance private month (string name) {This. name = Name;} Public String tostring () {return name;} public static final month Jan = new month ("January"), Feb = new month ("February "), MAR = new month ("March"), APR = new month ("Jun l"), May = new month ("may"), Jun = new month ("June "), jul = new month ("July"), Ug = new month ("August"), SEP = new month ("September"), Oct = new month ("October"), Nov = new month ("November "), dec = new month ("December"); public static final month [] month = {Jan, Feb, MAR, APR, May, Jun, Jul, Aug, SEP, Oct, nov, Dec}; public static final month number (INT order) {return month [order-1];} public static void main (string [] ARGs) {// curmonth is a month object, which can only be assigned a month object. This reflects the type security. Month curmonth = month. jan; system. out. println (curmonth); curmonth = month. number (12); system. out. println (curmonth); // This method also allows you to use = or equal () interchangeable, because each value of month has only one instance. System. out. println (curmonth = month. dec); system. out. println (curmonth. equals (month. dec); system. out. println (month. month [3]) ;}}

Running result:

13. interfaces can be nested in classes or other interfaces. Nested interfaces can have public and package access visibility. Meanwhile, both public and package access nested interfaces can be implemented as public, package access, and private Nested classes.

Class A {interface B {void fromb ();} interface d {void fromd ();} // nested interfaces can be private access permissions. // The advantage is that the method definition in the forced interface should not add any type information (that is, the upward transformation is not allowed). If you do not understand it, please refer to the final explanation. Private interface I {void fromi ();} // The Private nested interface can be implemented as private class J implements I {public void fromi () {system. out. println ("e. j. fromi () ") ;}}// the private nested interface can also be implemented as public class J1 implements I {public void fromi () {system. out. println ("e. j1.fromi () ") ;}/// combined with the Geti () and SETI () methods to achieve" upward transformation "?! Public I Geti () {return New J1 ();} public void SETI (I) {I. fromi ();} // nesting can be performed between interfaces, the interface nested in another interface can only be the public interface K {interface l {// This is also the public void froml () ;}} by default ();}}} public Class E implements A.D {public void fromd () {system. out. println ("e. fromd () ");} // internal class F public class F implements. B {public void fromb () {system. out. println ("e. f. fromb () ") ;}}// internal class G Protected class G implem Ents. B {public void fromb () {system. out. println ("e. g. fromb () ") ;}}// internal class I Private Class H implements. B {public void fromb () {system. out. println ("e. i. fromb () ") ;}} public static void main (string [] ARGs) {e = new E (); E. fromd (); // internal instantiation e.f F = E. new F (); F. fromb (); e.g G = E. new G (); G. fromb (); E. H = E. new H (); H. fromb (); // "implements the instantiation of the" public class J1 "of the private interface I. A. j1 J1 = new (). new J1 (); j1.fromi (); A = new A (); //. I I =. geti (); // type. I is not visible //. j1 J =. geti (); // cannot be. I to. j1 //. geti (). fromi (); // type. I is not visible.. SETI (. geti ());}}

Running result:

Geti (), returnPrivate interface referencePublic method. In Main (), multiple attempts to use the returned value failed. There is only one way to succeed, that isReturns the returned value to an object that has the right to use it.. In the preceding example, object a of object A is implemented through the SETI () method.

The above content is compiled from Java programming ideas. If any omission exists, please leave it blank!


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.