Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Java programming Interface

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to understand the Java programming interface". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Catalogue

Abstract classes and abstract methods

II. Interface

III. Multiple inheritance in Java

Fourth, extend the interface through inheritance

1. Name conflicts when combining interfaces

Fifth, adaptation interface

VI. Domains in the interface

7. Nested interfaces

1. Interfaces in a class

two。 Interfaces in Interfac

Interface and factory

Abstract classes and abstract methods

Abstraction: extract and generalize their common aspects, essential attributes and relations from concrete things, while abandoning individual and non-essential aspects, attributes and relations. This thinking process is called abstraction.

This sentence summarizes the abstract concept, but in Java, you can only give the definition of the method and not implement the concrete things of the method, and let the subclasses implement it according to the specific requirements.

In addition to abstract methods, abstract classes can also contain concrete variables and concrete methods. A class can be declared as an abstract class even if it does not contain abstract methods, preventing it from being instantiated.

Abstract classes cannot be instantiated, that is, you cannot use the new keyword to get an instance of an abstract class, and abstract methods must be implemented in subclasses.

Abstract summary rules:

An abstract class cannot be instantiated. If it is instantiated, an error will be reported and the compilation will fail. Only non-abstract subclasses of abstract classes can create objects.

Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.

The abstract method in the abstract class is only a declaration and does not contain the method body, that is, it does not give the concrete implementation of the method, that is, the concrete function of the method.

Constructors, class methods (methods decorated with static) cannot be declared as abstract methods.

A subclass of an abstract class must give a concrete implementation of the abstract method in the abstract class, unless the subclass is also an abstract class.

II. Interface

The interface keyword takes abstract concepts a step further, and the abstract keyword allows people to create one or more undefined methods in a class-provides the interface section. However, no specific implementations are provided, which are implemented by the successors of this class.

In an abstract class, you can contain one or more abstract methods; but in an interface, all methods must be abstract, without a method body, which is more "abstract" than an abstract class.

Interfaces are declared using the interface keyword, which can be seen as a special abstract class that specifies what a class must do rather than how it does it.

Compared with abstract classes, interfaces have some of their own features:

Only abstract methods can be defined in the interface, and these methods default to public abstract, so you can omit these modifiers when declaring methods. It is illegal to try to define instance variables, non-abstract instance methods and static methods in the interface.

There is no constructor in the interface and cannot be instantiated

One interface does not implement another interface, but can inherit multiple other interfaces. The multi-inheritance characteristic of interface makes up for the single inheritance of class.

The difference between interfaces and abstract classes:

Interface as a window of interaction between the system and the outside world, interface reflects a kind of specification. For the implementer of the interface, the interface specifies which services the implementer must provide (in the form of a method); for the caller of the interface, the interface specifies which services the caller can invoke and how to invoke these services (that is, how to invoke the method). When an interface is used in a program, an interface is a standard for coupling between multiple modules; when an interface is used between multiple applications, an interface is a standard for communication between multiple programs.

From a certain point of view, the interface is similar to the "general outline" of the whole system, it sets the standard that should be followed between the modules of the system, so the interface in a system should not be changed frequently. Once the interface changes, the impact on the whole system and even other systems will be radiant, resulting in most of the classes in the system need to be rewritten. Therefore, in a general application, the top level is the interface, followed by the abstract class implementation interface, and finally to the concrete class implementation.

Abstract class is different, abstract class as the common parent class of multiple subclasses in the system, it embodies the template design. Abstract class, as the abstract parent class of multiple subclasses, can be regarded as an intermediate product in the process of system implementation, which has implemented some of the functions of the system (those methods that have been provided in the abstract class). However, this product still can not be regarded as the final product and must be further improved.

In addition, there are the following differences in usage between interfaces and abstract classes:

Interfaces can only contain abstract methods, while abstract classes can contain ordinary methods.

Static methods cannot be defined in interfaces, but can be defined in abstract classes.

There are no constructors in the interface, and abstract classes can contain constructors. Constructors in abstract classes are not used to create objects, but rather have their subclasses call these constructors to complete initialization operations that belong to abstract classes.

An interface cannot contain initialization blocks, but an abstract class can contain initialization blocks.

Only static constants can be defined in the interface, and abstract classes can define both ordinary variables and static constants.

An interface can inherit multiple interfaces and a class can inherit only one class.

Abstract classes are mainly used to abstract categories, and interfaces are mainly used to abstract method functions. When focusing on the nature of things, use abstract classes, and when focusing on an operation, use interfaces.

III. Multiple inheritance in Java

An interface is not just a more purely abstract class, its goal is higher than that. Because there is no concrete implementation in the interface, there is no storage associated with the interface, so it is impossible to prevent the combination of multiple interfaces. In C++, the act of combining the interfaces of multiple classes is called multiple inheritance, but this can have many side effects because each class has a concrete implementation. In Java, you can perform the same behavior, but only one class can have a concrete implementation, so by combining multiple interfaces, C++ 's problems do not occur in Java.

To express such a meaning: "x belongs to a, to b, and to c."

Core reasons for using interfaces:

1)。 In order to be able to move up to multiple base types (and the resulting flexibility)

2)。 Prevent client programmers from creating objects for this class, and make sure that this is just an interface (for the same reason as using an abstract base class)

One of the questions this raises is whether you should use interfaces or abstract classes.

If you want to create a base class without any method definitions and member variables, you should choose the interface instead of the abstract class. In fact, if you know that something should be a base class, then the first choice should be the interface.

Fourth, extend the interface through inheritance 1. Name conflicts when combining interfaces

There is a small trap when implementing multiple inheritance. In the previous example, both CanFight and ActionCharacter have the same void fight () method. The problem is not that they have the same method, but what happens if they have different signatures (parameters) or return types?

/: interfaces/InterfaceCollision.javapackage object;interface I1 {void f ();} interface I2 {int f (int I);} interface I3 {int f ();} class C {public int f () {return 1;}} class C2 implements I1, I2 {public void f () {} public int f (int I) {return 1;} / overloaded} class C3 extends C implements I2 {public int f (int I) {return 1 } / / overloaded} class C4 extends C implements I3 {/ / Identical, no problem: public int f () {return 1;}} / / Methods differ only by return typeWanDisplicationclass C5 extends C implements I1 {}-- 23 return! Interface I4 extends I1, i3 {} /: ~-- 24 I1, the return value type of f () in i3 is inconsistent / / class C5 extends C implements I1 {/ / the method and accumulation method are named the same, but the return value of the method is not the same. / / int f () {/ / return 0 leading /} / /} / interface I4 extends I1, i3 {/ / overrides the same method name, but the return value is different. / @ Override// void f (); / /}

Because their method names are all the same, but the return values are different, method overloading cannot be implemented. Therefore, multiple inheritance and combination interfaces cannot be implemented.

Fifth, adaptation interface

One of the most attractive reasons for an interface is to allow many different implementations of the same interface.

The most common use of interfaces is to use policy design patterns. At this point you write a method to perform certain operations, and the method will accept an interface that you specify. Your main statement is: "you can call my method with any object you want, as long as your object follows my interface."

For example, the Scanner class of Java SE5, whose constructor receives a Readable interface.

Public Scanner (Readable source) {this (Objects.requireNonNull (source, "source"), WHITESPACE_PATTERN);} / Readable is a character source. The caller of the read method can use the characters in the Readable through CharBuffer. Public interface Readable {/ / adds input to the CharBuffer parameter. Public int read (java.nio.CharBuffer cb) throws IOException;}

Example1: implement the Readable interface.

Import java.io.IOException;import java.nio.CharBuffer;import java.util.Random;import java.util.Scanner;public class RandomWords implements Readable {private int count; public RandomWords (int count) {this.count = count;} private static Random random = new Random (47); private static final char [] capitals = "ABCDEFTHIGKLMNOPQRSTUVWXYZ" .toCharArray (); private static final char [] lowers = "abcdefghijklmnopqrstuvwxyz" .toCharArray (); private static final char [] vowerls = "aeiou" .toCharArray () @ Override public int read (CharBuffer cb) throws IOException {if (count-- = = 0) {return-1;} cb.append (capitals [class.nextInt (capitals.length)]); for (int I = 0; I < 4; iTunes +) {cb.append (vowerls [room.nextInt (vowerls.length)]); cb.append (lowers [room.nextInt (lowers.length)]);} cb.append ("); return 10 } public static void main (String [] args) {@ SuppressWarnings ("resource") Scanner scanner = new Scanner (new RandomWords (10)); while (scanner.hasNext ()) {System.out.println (scanner.next ());} / * output:YazeruyacFowenucorToeazimomRaeuuacioNuoadesiwHageaikuxRuqicibuiNumasetihKuuuuozogWaqizeyoy*/

Example2: for classes that do not implement Readable, you can use the adapter + proxy approach

Class RandomDoubles {private static Random rand = new Random (47); public double next () {return rand.nextDouble ();}} / /-import java.io.IOException;import java.nio.CharBuffer;import java.util.Random;import java.util.Scanner Public class Test {public static void main (String [] args) {Scanner s=new Scanner (new AdaptedRandomDoubles (7)); while (s.hasNext ()) {System.out.println (s.next ());} class AdaptedRandomDoubles extends RandomDoubles implements Readable {private int count; public AdaptedRandomDoubles (int count) {this.count=count } public int read (CharBuffer cb) throws IOException {if (count--==0) {return-1;} String result=Double.toString (this.next ()); cb.append (result); return result.length ();}} VI. Domain in the interface

Instance variables are all static final

7. Nested interfaces

The syntax of nesting interfaces in a class is quite obvious, and just like non-nested interfaces, you can have both public and package access visibility.

1. Interface {void f ();} class A {interface B {void f ();} public class BImp implements B {public void f () {}} private class BImp2 implements B {public void f () {}} public interface C {void f () in class } class CImp implements C {public void f () {}} private class CImp2 implements C {public void f () {} private interface D private class DImp implements D {public void f () {}} public class DImpl2 implements D {public void f () {}} public D getD ( ) {return new DImpl2 () } private D dRef; public void receive (D d) {dRef = d; dRef.f ();}} interface E {interface G {void f ();} / / Redundant "public" public interface H {void f ();} void g () / / cannot be private within an interface} public class NestingInterface {public class BImpl implements A.B {public void f () {}} class CImpl implements A.C {public void f () {} / cannot implement a private interface / / class DImpl implements A.D {/ / public void f () {/ /} Class EImpl implements E {public void g () {}} class EImpl2 implements E.G {public void f () {} class EG implements E.G {public void f () {} public static void main (String [] args) {An a = new A () Aa2 = new A (); / / Can't access A.D: cannot access private interface A.D /! A.D ad = a.getD (); / / Doesn't return anything but A.D: nothing can be returned except the private interface A.D. /! A.DImp2 di2 = a.getD (); / / the returned private interface A.D cannot be converted down to A.DImp2 / / Cannot access a member of the interface: members of the private interface A.D cannot be accessed / /! A.getD () .f (); / / Only another A can do anything with getD (): only another A can do anything with getD () a2.receive (a.getD ());}}

A.DImp2 can only be used by itself. You can't say that it implements a private interface D, so implementing a private interface is just one way to force the method definition in that interface not to add any type of information (that is, no upward transformation is allowed), that is, A.DImp2 cannot be converted to private interface D.

An interface can also be implemented as private, as seen in A.D.; a private interface cannot be implemented outside of the class that defines it

Give the return value to the object that has the right to use it. In this case, it is implemented by another A through the receiveD () method

An interface nested in another interface is automatically public and cannot be declared as private.

two。 Interface interface E {/ / can only be the default or public interface G {/ / defaults to public void f ();} / / Cannot be private within an interface: / /! Private interface I {}} class T2 implements E.G {public void f () {}} VIII, Interface and Factory

Interface is a way to achieve multiple inheritance, and a typical way to generate objects that follow an interface is the factory method design pattern

Through the complete separation of the factory method, interface and implementation, the implementation can be easily changed.

Interface Service / / Service interface, can have multiple implementations {void method1 (); void method2 ();} interface ServiceFactory / / factory interface, and can be implemented by multiple implementations {Service getService ();} class Implementation1 implements Service {/ / Service interface 1 public Implementation1 () {} public void method1 () {System.out.println ("Implementation1 method1");} public void method2 () {System.out.println ("Implementation1 method2") }} class Implementation1Factory implements ServiceFactory {/ / Factory 1 public Service getService () {return new Implementation1 ();}} implementation of class Implementation2 implements Service {/ / Service interface 2 public Implementation2 () {} public void method1 () {System.out.println ("Implementation2 method1");} public void method2 () {System.out.println ("Implementation2 method2") }} class Implementation2Factory implements ServiceFactory {/ / Factory 2 public Service getService () {return new Implementation1 ();}} public class Factories {/ / module public static void serviceConsumer (ServiceFactory fact) using service {Service s = fact.getService (); / / upward modeling, the factory will generate some kind of object that implements the interface s.method1 (); s.method2 () } public static void main (String [] args) {serviceConsumer (new Implementation1Factory ()); / / serviceConsumer (new Implementation2Factory ()); it is convenient to change the implementation}} / * output:Implementation1 method1Implementation1 method2Implementation2 method1Implementation2 method2*/

Anonymous inner class improvement

Interface Service {void method1 (); void method2 ();} interface ServiceFactory {Service getService ();} class Implementation1 implements Service {private Implementation1 () {} public void method1 () {System.out.println ("Implementation1 method1");} public void method2 () {System.out.println ("Implementation1 method2") } public static ServiceFactory factory = new ServiceFactory () {public Service getService () {return new Implementation1 ();}};} class Implementation2 implements Service {private Implementation2 () {} public void method1 () {System.out.println ("Implementation1 method1");} public void method2 () {System.out.println ("Implementation1 method2") } public static ServiceFactory factory = new ServiceFactory () {public Service getService () {return new Implementation2 ();}};} public class Factories {public static void serviceConsumer (ServiceFactory fact) {Service s = fact.getService (); s.method1 (); s.method2 ();} public static void main (String [] args) {serviceConsumer (Implementation1.factory) ServiceConsumer (Implementation2.factory);}} "how to understand the Java programming interface" ends here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report