Technology Sharing

[JAVA Introduction] Day 15 - Interface

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

[JAVA Introduction] Day 15 - Interface



Why are there interfaces?
As we all know, inheritance is to abstract the common features of subclasses into parent classes,Commonalities of the entire systemTo save code, however, there is also a situation: most subclasses have a commonality, but only a very small number of subclasses do not have this feature. If this commonality is written into the parent class and inherited, it will be unreasonable for these few subclasses.
For example, cats and dogs can swim, but rabbits can't. If we define a "swimming" method in the parent class, it is unreasonable for rabbits to inherit it. However, if cats and dogs write their own swimming methods, the format and naming of the two methods may be inconsistent. Therefore, we need to define a new concept to constrain the writing standards of the "swimming" methods in these two subclasses. At this time, we can define a "swimming" method.interface, define the abstract method swim() in the interface, and then connect the cat and dog to this interface to ensureUnification of code
To sum up, an interface is arule, when we need to define rules for multiple classes at the same time, we need to useinterface

1. Interface is an abstraction of "behavior"

An interface does not represent a class of things; an interface representsA rule, so the interface can be passed as an argument to a method.
"No matter if the mover is a truck, a tricycle, or even human labor, as long as he can accomplish the move, he is useful."

搬家(车的对象);
  • 1
搬家(搬家公司);
  • 1
public interface 运输 {
	...
}
  • 1
  • 2
  • 3
public void 搬家(运输的接口 c) {
	...
}
  • 1
  • 2
  • 3

2. Definition and use of interface

  • Interfaces are defined using the keyword interface.
public interface 接口名 {}
  • 1
  • Interfaces cannot be instantiated, which means that interfaces cannot be used to create objects.
  • The difference between interface and class isaccomplishRelationship, expressed through the implements keyword.
public class 类名 implements 接口名 {}
  • 1
  • A subclass (implementation class) of an interface either overrides all abstract methods in the interface or is itself an abstract class.
  • The implementation relationship between the interface and the class can beSingle Implementation, you can alsoMultiple Implementations
public class 类名 implements 接口名1 , 接口名2 {}
  • 1
  • An implementation class can implement multiple interfaces while inheriting a class.
public class 类名 extends 父类 implements 接口名1 , 接口名2 {}
  • 1

practise: Write standard Javabean classes with interfaces and abstract classes.

 青蛙		属性:名字,年龄		行为:吃虫子,蛙泳
 狗			属性:名字,年龄		行为:吃骨头,狗刨
 兔子		属性:名字,年龄		行为:吃胡萝卜
  • 1
  • 2
  • 3

Write the parent class first. Since the three subclasses eat different things, you can define eat() as an abstract method:

package oopInterface;

public abstract class Animal {
    private String name;
    private int age;

    public Animal() {
    }

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public abstract void eat();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

Write interface Swim:

package oopInterface;

public interface Swim {
    public abstract void swim();
}
  • 1
  • 2
  • 3
  • 4
  • 5

Write the frog class, pay attention to inheriting the parent class and overriding the abstract method of the parent class, and pay attention to implementing the swimming interface:

package oopInterface;

public class Frog extends Animal implements Swim {
    public Frog() {
        super();
    }

    public Frog(String name, int age) {
        super(name, age);
    }

    @Override
    public void swim() {
        System.out.println("青蛙在蛙泳。");
    }

    @Override
    public void eat() {
        System.out.println("青蛙在吃虫子。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Write the dog class, pay attention to inheriting the parent class and rewriting the abstract method of the parent class to implement the swimming interface:

package oopInterface;

public class Dog extends Animal implements Swim {

    public Dog(){
        super();
    }

    public Dog(String name, int age) {
        super(name,age);
    }
    @Override
    public void swim() {
        System.out.println("狗在狗刨。");
    }

    @Override
    public void eat() {
        System.out.println("狗在吃骨头。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Write the Rabbit class. Note that you only need to inherit the parent class and rewrite the abstract method. You do not need to implement the swimming interface (it cannot swim):

package oopInterface;

public class Rabbit extends Animal {

    public Rabbit() {
    }

    public Rabbit(String name, int age) {
        super(name, age);
    }

    @Override
    public void eat() {
        System.out.println("兔子在吃胡萝卜。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

Write a test class.

package oopInterface;

public class Test {
    public static void main(String[] args) {
        Frog f = new Frog("小绿",23);
        f.eat();
        f.swim();
        System.out.println(f.getName() + ", " + f.getAge());
        Dog d = new Dog("大D", 24);
        d.eat();
        d.swim();
        System.out.println(d.getName() + ", " + d.getAge());
        Rabbit r = new Rabbit("兔子", 30);
        r.eat();
        System.out.println(r.getName() + ", " + r.getAge());
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3. Characteristics of members in the interface

  • Member variables: Member variables in an interface can only beconstant, the public static final modifier is used by default (even if it is not written, it is automatically assumed to be so).
  • Constructor: InterfaceNoConstruction method.
  • Member methods: Before JDK7, they could only be abstract methods.defaultThe modifier is public abstract. After JDK8, methods with method bodies can be defined in interfaces. After JDK9, private methods can be defined in interfaces.

4. The relationship between interfaces and classes

  • The relationship between classes: inheritance relationship - only single inheritance is allowed, not multiple inheritance, but multi-layer inheritance is allowed.
  • The relationship between classes and interfaces: implementation relationship - you can have a single implementation or multiple implementations, and you can also implement multiple interfaces while inheriting a class.
  • The relationship between interfaces: inheritance relationship - it can be single inheritance or multiple inheritance.

Notice:
1. When a class implements an interface, it either implements all the abstract methods in the interface, or the class itself is also an abstract class.
2. A class can implement multiple interfaces. If multiple interfaces are implemented, you need toallTo implement the abstract methods of the interface.
3. Interfaces can inherit multiple interfaces. If a sub-interface inherits multiple interfaces and is then implemented by an implementation class, the implementation class must combine the sub-interface with all its parent interfaces.allAll abstract methods are implemented.

practise: Write standard Javabean classes with interfaces and abstract classes.

乒乓球运动员:姓名,年龄,学打乒乓球,说英语
篮球运动员:姓名,年龄,学打篮球
乒乓球教练:姓名,年龄,教打乒乓球,说英语
篮球教练:姓名,年龄,教打篮球
  • 1
  • 2
  • 3
  • 4
//Person类
package oopInterExp;

//因为直接创建顶层父类人的对象是没有意义的
//所以将其写为抽象类
public abstract class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Person() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
//Sporter类继承Person
package oopInterExp;

public abstract class Sporter extends Person {

    public Sporter(String name, int age) {
        super(name, age);
    }

    public Sporter() {
    }

    public abstract void learn();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
//Coach类继承Person
package oopInterExp;

public abstract class Coach extends Person {

    public Coach() {
    }

    public Coach(String name, int age) {
        super(name, age);
    }

    public abstract void teach();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
//SpeakEnglish接口
package oopInterExp;

public interface SpeakEnglishInter {
    public abstract void speakEnglish();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
//PingPongSporter继承Sporter,实现SpeakEnglish
package oopInterExp;

public class PingPongSporter extends Sporter implements SpeakEnglishInter {

    public PingPongSporter(String name, int age) {
        super(name, age);
    }

    public PingPongSporter() {
    }

    @Override
    public void learn() {
        System.out.println("学习乒乓球。");
    }

    @Override
    public void speakEnglish() {
        System.out.println("乒乓球运动员在说英语。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
//PingPongCoach继承Coach,实现SpeakEnglish
package oopInterExp;

public class PingPongCoach extends Coach implements SpeakEnglishInter {
    public PingPongCoach() {
    }

    public PingPongCoach(String name, int age) {
        super(name, age);
    }

    @Override
    public void teach() {
        System.out.println("教乒乓球。");
    }

    @Override
    public void speakEnglish() {
        System.out.println("乒乓球教练在说英语。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
//BasketballSporter继承Sporter
package oopInterExp;

public class BasketballSporter extends Sporter {

    public BasketballSporter(String name, int age) {
        super(name, age);
    }

    public BasketballSporter() {
    }

    public void learn() {
        System.out.println("学篮球。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
//BasketballCoach继承Coach
package oopInterExp;

public class BasketballCoach extends Coach {

    public BasketballCoach() {
    }

    public BasketballCoach(String name, int age) {
        super(name, age);
    }

    public void teach() {
        System.out.println("教篮球。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

5. New methods in the interface

5.1 Methods added to interfaces starting with JDK8

Before JDK7, only abstract methods can be defined in an interface.
The new feature of JDK8 is that methods with method bodies can be defined in interfaces (you can definedefaultMethod orStaticmethod).
The new features of JDK9 are: interfaces can be definedprivatemethod.

5.1.1 Default methods in interfaces

The method with method body defined in the interface is mainly forInterface upgradeConsider that the interface cannot be static, and new methods need to be added to it for upgrading. If these methods are abstract methods, then the implementation class also needs to implement these methods, which is very troublesome and difficult to synchronize. If the upgrade uses methods with method bodies, then the implementation class does not need to be modified additionally. If modification is required, it can also be modified by rewriting.

  • To define a default method in an interface, you need to use the keyword default Modification.
  • Format: public default return value type method name (parameter list) { }
  • Example: public default void show() { }
  • The default method is not an abstract method and does not need to be overridden. However, if it is overridden, the default keyword must be removed when overriding.
  • public can be omitted, but default cannot be omitted.
  • If multiple interfaces are implemented and there are default methods with the same name in multiple interfaces, then the subclass must override the method (failure to override will cause conflicts).

Interface Inter1:

package oopInterface5;

public interface Inter1 {
    public abstract void method();
    public default void default_method() {
        System.out.println("Inter1接口中的默认方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Interface Inter2:

package oopInterface5;

public interface Inter2 {
    public default void default_method() {
        System.out.println("Inter2接口中的默认方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

The two default methods have the same name. If the implementation class implements both interfaces at the same time, you must override this default method!

package oopInterface5;

public class InterImpl implements Inter1, Inter2 {

    @Override
    public void method() {
        System.out.println("抽象方法的实现");
    }

    @Override
    public void default_method() {
        System.out.println("重写接口中的默认方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Test class:

package oopInterface5;

public class Test {
    public static void main(String[] args) {
            InterImpl ii = new InterImpl();
            ii.method();				//抽象方法的实现
            ii.default_method();		//重写接口中的默认方法
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
5.1.2 Static methods in interfaces

JDK8 and later allow static methods to be defined in interfaces, which need to be modified with static.
InterfaceStatic methodsThe definition format is:

  • public static return value type method name (parameter list) { }
  • Example: public static void show() { }

Notes on static methods in interfaces:

  • Static methods can only be accessed throughInterface NameCalling cannot be done by implementing class name or object name.
  • public can be omitted, but static cannot be omitted.

Write an interface:

package oopInterface6;

public interface Inter {
    public abstract void method();

    public static void static_method() {
        System.out.println("接口中的静态方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Write an implementation class that also has a static method with the same name as the method in the interface, but this is not an override because static methods cannot be overridden:

package oopInterface6;

public class InteImpl implements Inter {
    @Override
    public void method() {
        System.out.println("重写接口中的抽象方法");
    }

    //这不叫重写
    public static void static_method() {
        System.out.println("我不是重写的Inter接口中的静态方法");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

But in fact, the two are different methods.

package oopInterface6;

public class Test {
    public static void main(String[] args) {
        InteImpl ii = new InteImpl();
        ii.method();						  //重写接口中的抽象方法
        Inter.static_method();               //调用接口中的静态方法
        InteImpl.static_method();           //调用实现类中的一个同名的静态方法
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5.2 New methods added to interfaces starting with JDK9

5.2.1 Defining Private Methods in Interfaces
  • Format 1: private return value type method name (parameter list) { }
  • Example 1: private void show() { }
  • Usage: Serve the default method.
package oopInterface7;

public interface InterA {
    public default void show1() {
        System.out.println("show1开始执行");
        show3();
    }

    public default void show2() {
        System.out.println("show2开始执行");
        show3();
    }

    //普通的私有方法,给默认方法服务的
    private void show3() {
        System.out.println("记录程序在运行过程中的各种细节,这里有100行代码。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • Format 2: private static return value type method name (parameter list) { }
  • Example 2: private static void method() { }
  • Usage: Serve static methods.
package oopInterface7;

public interface InterB {
    public static void show1() {
        System.out.println("show1开始执行");
        show3();
    }

    public static void show2() {
        System.out.println("show2开始执行");
        show3();
    }

    //普通的私有方法,给静态方法服务的
    private static void show3() {
        System.out.println("记录程序在运行过程中的各种细节,这里有100行代码。");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

6. Interface Application

1. Interfaces represent rules and are the abstraction of behaviors. If you want a class to have a behavior, just let the class implement the corresponding interface.
2. When a method parameter is an interface, you can pass the interfaceAll objects of the implementing class, this approach is called interface polymorphism.

7. Adapter Design Pattern

  • Design Pattern is a set of repeatedly used, well-known, cataloged, and summarized code design experiences. Design patterns are used to reuse code, make it easier for others to understand the code, and ensure code reliability and program reusability.

Adapters can be used to simplify the code and avoid the inconvenience caused by too many abstract methods in the interface and we only need to use some of them.
The general steps for writing are:
1. Write the intermediate class XXXAdapter to implement the corresponding interface.
2. Provide empty implementation for abstract methods in the interface.
3. Let the actual implementation class inherit the intermediate class and rewrite the required methods.
4. In order to avoid other classes from creating objects of the adapter class, the intermediate adapter class is modified with abstract.

interface:

package AdapterDesignPattern;

public interface Inter {
    public abstract void method1();
    public abstract void method2();
    public abstract void method3();
    public abstract void method4();
    public abstract void method5();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

Adapter class:

package AdapterDesignPattern;

public abstract class InterAdapter implements Inter {
    @Override
    public void method1() {

    }

    @Override
    public void method2() {

    }

    @Override
    public void method3() {

    }

    @Override
    public void method4() {

    }

    @Override
    public void method5() {

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

Implementation class:

package AdapterDesignPattern;

public class InterImpl extends InterAdapter {
    //我需要用到哪个方法,就重写哪个方法就可以了
    @Override
    public void method5() {
        System.out.println("只要用第五个方法");
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10