Java object oriented: Interface

1, Interface

1. Interface Overview

An interface is a reference type in the Java} language. It is a collection of abstract methods and constant value definitions. If a class encapsulates member variables, construction methods and member methods, the interface mainly encapsulates methods, including abstract methods (JDK 7 and above), default methods and static methods (JDK 8), and private methods (JDK 9).

An interface is a set of rules defined by a specification. Inheritance is a yes / no relationship, while interface implementation is a yes / no relationship.

The essence of an interface is a contract, standard and specification. Just like our laws, everyone should abide by them after they are formulated.

2. Definition of interface

It is similar to defining classes, but uses the {interface} keyword. It will also be compiled into Class file, but it must be clear that it is not a class, but another reference data type.

Tips: reference data type: array, class, interface, etc.

3. Use of interface

It cannot create objects, but can be implemented (similar to inherited). A class that implements an interface (which can be regarded as a subclass of the interface) needs to implement all the abstract methods in the interface. After creating this class object, you can call the method, otherwise it must be an abstract class.

4. Members of the interface

Constant values and abstract methods. An interface is a collection of abstract methods and constant value definitions.

5. Characteristics of interface

(1) the interface is defined by interface;

(2) all member variables in the interface are modified by public static # final by default;

(3) all abstract methods in the interface are modified by public abstract by default;

(4) there is no constructor in the interface, which means that the interface cannot be instantiated;

(5) the interface adopts multi inheritance mechanism;

 

2, Define format

1. Definition of interface

Define format:

[Permission modifier] interface Interface name {
   The member list of the interface is as follows:
    // Abstract method
    // Default method
    // Static method
    // Private method
}

    

  2,

3, Members in interface

1. JDK7 and previous members

    JDK1.7 and before, there are two kinds of interface members: static constants and abstract methods (JDK7 +)

Global static constant: the "member variable" can also be defined in the interface, but it must be decorated with the three keywords public static final (which can be omitted). In fact, it is the constant in the interface.

Public abstract method: use publc abstract keyword to modify, and (can be omitted) there is no method body. This method is used by subclass implementations.

Syntax format:

public static final Data type variable name = Value;
public abstract Return value type method name (parameter list);

  

    Demo:

1 public interface InterFaceName {
2    public static final long MAX_SPEED = 7900000;  //constant
3   public abstract void method();                 //Abstract method
4 }

Tips: once the final keyword is used for modification, the description cannot be changed.

Precautions:

(1) constants in the interface can be omitted from public static final. Note that they are also modified in this way when omitted; (all variables in the interface are constants)

(2) constants in the interface must be assigned; Assignment cannot be omitted;

(3) the names of constants in the interface shall be in full uppercase letters and separated by underscores. (recommended naming rules)

 

2. Members after JDK8

    JDK1. After 8, the interface enhances two members: default method and static method (JDK8 +)

Default method: use the default modifier and cannot be omitted. It can be called or overridden by subclasses.

Syntax format:

public default Return value type method name(parameter list) {
    Method body
}

  

Static method: it is decorated with public static and cannot be omitted. It can be called directly by the interface.

    Demo:

1 public interface InterFaceName {
2     public default void method() {
3         // Execute statement
4     } 
5     public static void method2() {
6         // Execute statement
7     }
8 }

Extension:

(1) why does Java 8 allow static methods to be defined in interfaces?

Use the static keyword to decorate. You can call static methods directly through the interface and execute their method bodies.

Because after JDK has developed for a period of time, it is found that there are many group API s in the class library, such as Array and Arrays classes, Collection interface and Collections tool classes.

General tool classes are static methods. These static methods basically serve the corresponding interface above. When such static methods are directly moved to the interface definition, it is good to reduce the emergence of such tool classes.

 

(2) why does Java 8 allow default methods to be defined in interfaces?

The default method is decorated with the default keyword. Can be called by implementing class objects.

Because sometimes, most of the implementation classes of an interface have the same implementation code for the abstract methods of the interface, which is very troublesome to write several times. That is, the default method is that the original abstract method has a default implementation.

If the implementation of the implementation class is the same as the interface, it does not need to be rewritten. If it is different, it can be rewritten.

 

  3,JDK9

    JDK1. After 9, add two interface members: private method and private static method (JDK9 +)

Private method: private modification is used for calling the default method or static method in the interface.

Private static method: decorated with private static, it can be called by the default method or static method in the interface.

    Demo:

public interface InterfaceTest {

	private void method5() {
		System.out.println("Private method");
	}
	
	private static void method6() {
		System.out.println("Private static method");
	}
}

  

 

4, Implementation of interface

1. Implementation of interface

(1) the relationship between class and interface is implementation relationship, that is, class implements interface. This class can also be called implementation class of interface or subclass of interface.

(2) the actions of the implementation are like inheritance and the format is similar, but the keywords are different. The implementation uses the keyword "implements".

(3) define the syntax format of Java class: write extensions first, and then implement;

        class SubClass extends SuperClass implements InterfaceA{ }

(4) a class can implement multiple interfaces, and interfaces can also inherit other interfaces;

(5) the class implementing the interface must provide the specific implementation contents of all methods in the interface before instantiation. Otherwise, it is still an abstract class;

(6) the main purpose of the interface is to be implemented by the implemented class; Similar to inheritance, there is polymorphism between interface and implementation class;

(7) Java classes can implement multiple interfaces -- >, which makes up for the limitation of Java single inheritance;

(8) interfaces can be inherited from one another, and multiple interfaces can be inherited;

(9) interface and class are in parallel relation, or can be understood as a special class. In essence, an interface is a special abstract class. This abstract class only contains the definitions of constants and methods (before JDK7), without the implementation of variables and methods.

2. Non Abstract subclass implementation interface

(1) all abstract methods in the interface must be rewritten;

(2) it inherits the default method of the interface, that is, it can be called directly or overridden;

(3) static methods in the interface cannot be rewritten;

Implementation format:

class Class name implements Interface name {
    // Rewrite the abstract method in the interface [required]
    // Override the default method in the interface [optional]
// Static methods cannot be overridden }

 

 

3. Abstract method

All abstract methods in the interface must be implemented.

    Demo:

 1 // Define interface:
 2 public interface LiveAble {
 3     // Define abstract methods
 4     public abstract void eat();
 5     public abstract void sleep();
 6 }
 7 
 8 // Define implementation classes
 9 public class Animal implements LiveAble {
10     @Override
11     public void eat() {
12         System.out.println("Eat something");
13     }
14     @Override
15     public void sleep() {
16         System.out.println("Sleep at night");
17     }
18 }

 

4. Default method

It can be inherited or rewritten, but it can only be one of two, and can only be called through the object implementing the class;

(1) inherit the default method

      Demo:

 1 // Define interface
 2 public interface LiveAble {
 3     public default void fly(){
 4         System.out.println("Fly in the sky");
 5     }
 6 }
 7 
 8 // Define implementation classes
 9 public class Animal implements LiveAble {
10     // Inheritance, nothing to write, direct call
11 }
12 
13 // Test class
14 public class InterfaceDemo {
15     public static void main(String[] args) {
16         // Create subclass object
17         Animal a = new Animal();
18         // Call default method
19         a.fly();
20     }
21 }
22 Output result:
23 Fly in the sky

 

(2) override the default method

      Demo:

 1 // Define interface
 2 public interface LiveAble {
 3     public default void fly(){
 4         System.out.println("Fly in the sky");
 5     }
 6 }
 7 
 8 // Define implementation classes
 9 public class Animal implements LiveAble {
10     @Override
11     public void fly() {
12         System.out.println("Fly freely");
13     }
14 }
15 
16 // Define test class
17 public class InterfaceDemo {
18     public static void main(String[] args) {
19         // Create subclass object
20         Animal a = new Animal();
21         // Call override method
22         a.fly();
23     }
24 }
25 Output result:
26 Fly freely

 

 

5. Static method

Static vs Class files are related, and can only be called with the interface name, not through the class name of the implementation class or the object of the implementation class.

Syntax format:

public static Return value type method name(parameter list) {
    Method body
}

  

    Demo:

 1 // Define interface
 2 public interface LiveAble {
 3     public static void run(){
 4         System.out.println("Run~~~");
 5     }
 6 }
 7 
 8 // Define implementation classes
 9 public class Animal implements LiveAble {
10     // Static methods cannot be overridden
11 }
12 
13 // Define test class
14 public class InterfaceDemo {
15     public static void main(String[] args) {
16     // Animal.run(); // [Error] unable to inherit method,Can't call
17     LiveAble.run(); //
18     }
19 }
20 Output result:
21 Run~~~

 

6. Private method and private static method

    • Private method: only the default method can be called;
    • Private static method: default method and static method can be called;

Syntax format:

private Return value type method name(parameter list){ Method body}            Common private method
private static Return value type method name(parameter list) { Method body}    Static private method

If there are multiple default methods in an interface and there are duplicate contents in the methods, they can be extracted and encapsulated into private methods for the default methods to call.

    Demo:

 1 public interface LiveAble {
 2     default void func(){
 3         func1();
 4         func2();
 5     }
 6     private void func1(){
 7         System.out.println("Run~~~");
 8     }
 9     private void func2(){
10         System.out.println("Run~~~");
11     }
12 }

 

  7,

  8,

5, Multiple implementations of interfaces (interface conflicts)

In the inheritance system, a class can inherit only one parent class. For interfaces, a class can implement multiple interfaces, which is called multiple implementation of interfaces. Moreover, a class can inherit a parent class and implement multiple interfaces at the same time.  
Implementation format:

class Class name [extends Parent class name] implements Interface name 1,Interface name 2,Interface name 3... {
    // Rewrite the abstract method in the interface [required]
    // Override the default method in the interface [optional if there is no duplicate name]
}

1. Abstract method

When there are multiple abstract methods in the interface, the implementation class must override all abstract methods.

If the abstract method has duplicate names, it only needs to be rewritten once.

    Demo:

 

 1 // Define interface
 2 interface A {
 3     public abstract void showA();
 4     public abstract void show();
 5 }
 6 interface B {
 7     public abstract void showB();
 8     public abstract void show();
 9 }
10 
11 //Define implementation classes
12 public class C implements A,B{
13     @Override
14     public void showA() {
15         System.out.println("showA");
16     }
17     @Override
18     public void showB() {
19         System.out.println("showB");
20     }
21      @Override
22      public void show() {
23         System.out.println("show");
24     }
25 }

 

 

 

2. Default method (interface conflict)

When a class implements two or more interfaces at the same time, and default methods with the same method signature appear in these interfaces,

You must make a choice in this class:

(1) retain one and abandon the other;

(2) do not use both, completely rewrite one;

    Demo:

 1 interface A{
 2     public default  void test(){
 3         System.out.println("aaa");
 4     }
 5 }
 6 interface B{
 7     public default  void test(){
 8         System.out.println("bbb");
 9     }
10 }
11 class C implements A,B{
12         //Choose one: keep one and discard the other
13         A.super.test();  //retain A Implementation of interface
14         B.super.test();  //retain B Implementation of interface
15 }
16 
17 class C1 implements A,B{
18     //Option 2: do not use either, completely rewrite one
19     public void test(){
20         System.out.println("ccc");
21     }
22 }

 

3. Static method

Static methods with the same name in the interface will not conflict because they can only be accessed through their respective interface names.

4. Priority issues

When a class inherits a parent class and implements several interfaces, what should be done if the member method in the parent class has the same signature as the method in the interface?

How to choose?

(1) default selection: the compiler selects the method in the parent class by default;

(2) re select the reserved interface;

(3) completely rewrite by yourself;

    Demo:

 1 class Father{
 2     public void test(){
 3         System.out.println("ffff");
 4     }
 5 }
 6 interface D{
 7     public default void test(){
 8         System.out.println("dddd");
 9     }
10 }
11 class Son1 extends Father implements D{
12     //Option 1: the default option is to keep the parent class
13 }
14 
15 class Son2 extends Father implements D{
16     //Option 2: change the interface
17         public void test() {
18             D.super.test();
19         }
20 }
21 
22 class Son3 extends Father implements D{
23     // Completely rewrite yourself
24          public void test() {
25               System.out.println("ssss");
26         }
27 }

 

  5,

6, Multiple inheritance of interfaces

One interface can inherit another or more interfaces, which is similar to the inheritance between classes.

Interface inheritance uses the extends keyword, and the child interface inherits the methods of the parent interface.

If the default method of the parent interface has a duplicate name, the child interface needs to be rewritten once.

  Demo:

 1 //Define parent interface
 2 interface A {
 3     public default void method(){
 4         System.out.println("AAAAA");
 5     }
 6 }
 7 interface B {
 8     public default void method(){
 9         System.out.println("BBBBB");
10     }
11 }
12 
13 // Sub interface definition
14 interface D extends A,B{
15     @Override
16     public default void method() {
17         System.out.println("DDDDD");
18     }
19 }

 

Tips: when the sub interface overrides the default method, the default keyword can be retained; When subclasses override the default method, the default keyword cannot be reserved.

  1,

  2,

  3,

  4,

7, Characteristics of members in interface

1. In the interface, member variables cannot be defined, but constants can be defined, and their values cannot be changed. The default modification is "public static final".

2. There is no construction method in the interface, so objects cannot be created.

3. There is no static code block in the interface.

4. If a class directly inherits the methods in the parent class and conflicts with the default methods in the interface, the methods in the parent class shall prevail.

8, Characteristics of interface

1. The interface is a standard, which is used to be observed, that is, used to be implemented. When implementing the interface, the implementation class must implement / rewrite all abstract methods, otherwise the implementation class must be an abstract class;

2. There must be no construction method for the interface, that is to say, objects cannot be created directly;

3. The reference variable of interface type and the object of implementation class constitute polymorphic reference;

4. When a class inherits the parent class, Java only supports single inheritance, but when a class implements an interface, it can implement multiple interfaces at the same time;

5. If a class inherits the parent class and implements the interface at the same time, it is required to inherit the class first and implement the interface later;

[Modifier] class Implementation class  extends Parent class  implements Parent interfaces{}

  

6. In Java, interfaces can also inherit multiple interfaces;

[Permission modifier] interface Sub interface  extends Parent interfaces{ }

  

 

9, Common interview questions

1. Topic 1

 1 interface A {
 2     int x = 0;
 3 }
 4 
 5 class B {
 6     int x = 1;
 7 }
 8 
 9 class C extends B implements A {
10     public void pX() {
11         System.out.println(x);   //If the compilation fails, the x It is not clear whether it is in the interface or in the class
12     }
13 
14     public static void main(String[] args) {
15         new C().pX();
16     }
17 }
18 
19 Modification:
20   If you want to use variables in a class: System.out.println(super.x);//1
21    If you want to use variables (constants) in the interface: System.out.println(A.x);//0

2. Topic 2

  3,

  4,

  5,

  6,

10, Abstract classes and interfaces

1. Comparison between abstract classes and interfaces

    

 

 

 

  2,

 

Tags: Java

Posted by vinodkalpaka on Tue, 03 May 2022 17:45:14 +0300