定义和使用含有泛型的接口
定义和使用含有泛型的接口
定义格式∶
修饰符interface接口名<代表泛型的变量>{}

/*
  定义含有泛型的接口
 */
public interface GenericInterface<I> {
    public abstract void method(I i);
}
public class GenericInterfaceImpl1 implements GenericInterface<String>{ @Override public void method(String i) { System.out.println(i); } }
public class GenericInterfaceImpl2<I> implements GenericInterface<I>{ @Override public void method(I i) { System.out.println(i); } }
/* * 测试含有泛型的接口 */ public class Demo04GenericInterface { public static void main(String[] args) { //创建GenericInterfaceImpl1对象 GenericInterfaceImpl1 gi1 = new GenericInterfaceImpl1(); gi1.method("字符串");//字符串 //创建GenericInterfaceImpl1对象 GenericInterfaceImpl2<Integer> gi2 = new GenericInterfaceImpl2<>(); gi2.method(8); GenericInterfaceImpl2<Double> gi3 = new GenericInterfaceImpl2<>(); gi3.method(8.8); } }
public class GenericClass<E> { private E name; public E getName() { return name; } public void setName(E name) { this.name = name; } }
public class Demo02Test { /** * 测试类 * */ public static void main(String[] args) { //不写泛型默认为Object类型 GenericClass gc = new GenericClass(); gc.setName("qqqq"); Object name = gc.getName(); System.out.println(name); /** * 创建GenericClass对象 泛型使用Integer类型 */ GenericClass<Integer> gc2 = new GenericClass<Integer>(); gc2.setName(1); Integer name1 = gc2.getName(); System.out.println(name1); /** * 创建GenericClass对象,泛型使用String类型 */ GenericClass<String> gc3 = new GenericClass<String>(); gc3.setName("qqqqqqqq"); String name2 = gc3.getName(); System.out.println(name2); } }
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号