当前位置:网站首页>Two implementation methods of generic interface

Two implementation methods of generic interface

2022-06-12 15:18:00 A_ M amu

Generic interface

stay JDK1.5 after , Not only can you declare generic classes , You can also declare generic interfaces , The syntax for declaring generic interfaces is similar to that for declaring generic classes , Also add... After the interface name <T>, The format is as follows :

[ Access right ] interface The name of the interface < Generic identity >{

}

Two implementations of generic interfaces

After the generic interface is defined , To define subclasses of this interface , There are two ways to define subclasses of generic interfaces , One is to declare generics directly after subclasses , The other is to explicitly give generic types in the interface implemented by subclasses .

package com.am.demo05;

/**
 * @program: java senior - Generic 
 * @description:
 * @author:  Amur 
 * @create: 2021-12-20 15:20
 **/
public class Test05 {
    public static void main(String[] args) {
         USB<Integer> a=new Upan<>();

         USB<String> b=new Mouse();
    }
}
// Generic interface .
interface USB<T>{

    public T show();

}
// This generic type is also used when creating classes 
class Upan<T> implements USB<T>{
    @Override
    public T show() {
        return null;
    }
}
// Specify specific data types for generic interfaces when creating classes .
class Mouse implements USB<String>{
    @Override
    public String show() {
        return null;
    }
}

Generic methods

All the generic operations learned earlier are to generize the entire class , But you can also define generic methods in classes .== The definition of a generic method has nothing to do with whether the class it belongs to is a generic class ==, The class can be generic , It can also not be a generic class .   

The format of generic methods :  

 public < Generic identity > Generic identity Method name (){

}

public class Test {
    public static void main(String[] args) {
        String hello = fun("hello");
    }
    public static <T> T   fun(T t){
        return t;
    }
}

原网站

版权声明
本文为[A_ M amu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010502355190.html