跟王老师学泛型(四):定义泛型接口及实现

定义泛型接口及其实现

主讲教师:王少华 QQ群:483773664

学习目标

1、泛型接口

2、实现泛型接口的三种情况

一、定义接口

1
2
3
public interface Generator<T> {
     public T next();
}

二、实现这个接口

1
2
3
4
5
6
7
8
9
10
public class FruitGenerator implements Generator<String> {
 
     private String[] fruits = new String[]{ "Apple" , "Banana" , "Pear" };
 
     @Override
     public String next() {
         Random rand = new Random();
         return fruits[rand.nextInt( 3 )];
     }
}

三、调用

1
2
3
4
5
6
7
8
9
10
public class Main {
 
     public static void main(String[] args) {
         FruitGenerator generator = new FruitGenerator();
         System.out.println(generator.next());
         System.out.println(generator.next());
         System.out.println(generator.next());
         System.out.println(generator.next());
     }
}

四、实现接口的三种情况

1
2
3
4
5
6
7
8
9
public class FruitGenerator<T> implements Generator<T>{
 
     @Override
     public T next() {
         // TODO Auto-generated method stub
         return null ;
     }
 
}
1
2
3
4
5
6
7
8
9
public class FruitGenerator implements Generator<String>{
 
     @Override
     public String next() {
         // TODO Auto-generated method stub
         return null ;
     }
 
}
1
2
3
4
5
6
7
8
public class FruitGenerator implements Generator{
 
     @Override
     public Object next() {
         // TODO Auto-generated method stub
         return null ;
     }
}

五、学习视频网址:

http://edu.51cto.com/course/course_id-6083.html





来自为知笔记(Wiz)


你可能感兴趣的:(java,接口,border,false)