Java -- interface definition and examples

Abstract and interface appear frequently in both ordinary study and job interview. This paper combines the previous article Java -- abstract definitions and examples Learning interface.

Through this article, you will gain: (1) the basic concept of interface (2) what is the difference between abstraction and interface

1: Overview

Interface is an abstract type and a collection of abstract methods in JAVA programming language. An interface cannot be instantiated but can be implemented. A class that implements an interface must implement all the methods described in the interface, otherwise it must be declared as an abstract class.

  • Interfaces cannot be used to instantiate objects
  • Interface has no constructor
  • All methods in the interface must be abstract methods, which are implicitly abstract (they can only be public abstract and can be omitted)
  • All variables in the interface are implicitly specified as public static final
  • Interfaces are not inherited by classes, but implemented by classes

Definition: interface interface name (note the difference between @ interface and user-defined annotation)

2: Example (followed by abstract example)

In addition to feeding water to the animals, farmers also want snakes and tigers to hunt.

  • Bring animal (animal a, string destination) bring animal a to a certain place

  • feedAnimal(Animal hunt, Animal a) throw animal a to animal hunt

analysis:

If you want to achieve polymorphism, according to the previous example, you need to add hunt() method to Animal. But this will cause Goat and Rabbit to inherit hunt() method (because ordinary classes inherit abstract classes and must implement all of them). In fact, the lovely white Rabbit eats grass and doesn't hunt. So at this time, we think of the multi inheritance feature of the interface. The specific code is as follows (the code is adjusted on the basis of the previous Abstract example code):

1. Add a hunting interface (generics are used here. I silently pick up the book and review generics / (o) / ~ ~)

public interface Huntable<T>{
    void hunt(T o);
}

2.Tiger and Snake implement the hunting interface and the methods in the interface

class Tiger extends Mammal implements Huntable<Animal>{
    private static String name="tiger";

    @Override
    String getName() {
        return this.name;
    }

    @Override
    void move(String destination) {
        System.out.println("tiger move to "+destination+".");
    }

    @Override
    void drink() {
        System.out.println("tiger lower it is head and drink");
    }

    @Override
    public void hunt(Animal animal) {
        System.out.println("tiger hunt "+animal.getName()+" and eat");
    }
}


class Snake extends Reptile implements Huntable<Animal> {
    private static String name="snake";

    @Override
    String getName() {
        return this.name;
    }

    @Override
    void move(String destination) {
        System.out.println("snake move to "+destination+".");
    }

    @Override
    void drink() {
        System.out.println("snake dived into and drink");
    }

    @Override
    public void hunt(Animal animal) {
        System.out.println("snake hunt "+animal.getName()+" and eat");
    }
}

3. Methods for farmers to add hunting animals

class Farmer{
    public void bringWater(String destination){
        System.out.println("Farmer bring water to " + destination + ".");
    }

//New join
    public void bringAnimal(Animal animal,String destination){
        System.out.println("Farmer bring "+ animal.getName()+" to "+destination);
    }
    public void feedWater(Animal a){ // polymorphism
        this.bringWater("Feeding Room");
        a.move("Feeding Room");
        a.drink();
    }
// New join
    public void huntAnimal(Huntable hunt,Animal animal){
        this.bringAnimal(animal,"hunting root");
        Animal huntAnimal=(Animal) hunt;
        huntAnimal.move("hunting room");
        hunt.hunt(animal);
    }

}

4. Test

class Test{
    public static void main(String[] args) {
        Farmer fm=new Farmer();
        Goat goat=new Goat();
        Tiger tiger=new Tiger();

        fm.huntAnimal(tiger,goat);
    }
}

Execution result:

In the chestnuts mentioned above, it is not difficult to find that the main feature of the interface is the realization of multi inheritance. Generics are used in the interface, because in addition to animals that can hunt, some plants also have hunting characteristics, such as man eating grass and fly trap. More parameter types can be received through generics.

The difference between abstraction and interface?? (high frequency interview questions) ❤)

(1) Class can implement multiple interfaces, but can only inherit one abstract class

(2) All methods in the interface are implicitly abstract, and abstract classes can contain both abstract and non abstract methods

(3) The attributes defined in the interface are final, and the abstract class can contain non final attributes

  • Attributes defined in the interface: 1): attribute default modifier public static final # 2): must be initialized when defining # 3) attributes defined in the interface are equal to constants and variables cannot be defined
  • Final keyword: 1) final modifies a class, which cannot be inherited; 2) modifies a method, which can be inherited, but the class cannot be overridden; 3) modifies an attribute, which is equivalent to a constant
  • static keyword: 1) modify variable, class variable. Access {2) modification methods and class methods through "class name. Class variable name". Access through "class name. Method name"

(4) The methods in the interface are public by default, and the abstract class members can be private,protected or public

Summary:

final and static are just simple learning, including generics, which need to be further deepened. Knowledge is accumulated bit by bit. Learning this is related to that, and finally realize your own knowledge system. Recently, I began to feel that I can't stick to Baidu style development, so I hope to write high-quality code in the project development that can be applied by consolidating my previous knowledge a little. *** ❤

Keywords: Java

Added by day_tripperz on Wed, 09 Mar 2022 13:17:57 +0200