54. Generic Interfaces

Generic interface definition format:
    interface interface name <declare custom generic type>{
        
    }

Notes for generic interface:
    1. The specific data type of the custom generic type on the interface is specified when an interface is implemented
    2. Custom generics in the interface If the specific data type is not specified when implementing the interface, the default is Object type.

If we still don't know the data type we want to operate when we implement the interface, I have to wait until the implementation is created. class when specifying the data type.
The specific data type format of the extended interface custom generic:
    class class name <declared custom generic> implements interface name <declared custom generic>{
    
    }

For example:
    class Demo1<T> implements Dao<T>{
    
    }

Requirements: Add 1 to all elements in a collection of type Integer

// Define generic interface 
interface AddInterface<T> {
     public Integer add(T t);
}

// implement class 
class Math1<T> implements AddInterface<T> {

    @Override
    public Integer add(T t) {
        return (Integer)t+1;
    }
}
public class Demo4 {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        Iterator <Integer> it = list.iterator();
         // Instantiate the implementation class 
        Math1<Integer> m = new Math1<Integer> ();
         while (it.hasNext()) {
            System.out.println(m.add(it.next()));
        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325506520&siteId=291194637