在具体使用时,可以分为泛型接口、泛型类和泛型方法
第一、泛型类
public class javaMainTest {
public static void main(String[] args) {
//不在实例化对象的时候去指定类型有一个好处,就是在调用不同方法的时候可以传不同类型的参数。
Dog dog = new Dog();
dog.eat("shit");
dog.play(33);
Dog<String> dog1 = new Dog<>();
dog1.eat("shit2");
}
}
class Dog<T>{
public void eat(T t){
System.out.println("eat = " + t);
}
public void play(T t){
System.out.println("play = " + t);
}
}
衍生:类的继承
public class javaMainTest {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat("shit");
dog.play(100);
Dog<String> dog1 = new Dog<>();
dog1.eat("shit2");
dog1.play("bone");
}
}
//父类的泛型类型一定要和子类的类型是一样的
class Dog<T> extends Animal<T>{
public void eat(T t){
System.out.println("eat = " + t);
}
}
class Animal<E> {
public void play(E e){
System.out.println("play = " + e);
}
}
第二、泛型方法
public class javaMainTest {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat("shit");
dog.sleep(122);
dog.sleep("122");
Dog.age(23);
Dog.age("23");
System.out.println("age =" + dog.age1("33"));
}
}
class Dog<T>{
public void eat(T t){
System.out.println("eat = " + t);
}
//<W>就相当于是对方法里面的参数的类型进行声明一样,这个类型在调用方法的时候确定 第一个W必须有 第二个W可有可无
public<W> void sleep(W w){
System.out.println("sleep = " + w);
}
public static <R> void age(R r){
System.out.println("age = " + r);
}
//<R> R age1(R r) 第一个相当于类型声明,第二个是返回值 第三个是参数声明
public <R> R age1(R r){
System.out.println("age = " + r);
return r;
}
}
第三、泛型接口
public class javaMainTest {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat("shit");
dog.play(33);
}
}
class Dog<T> implements Animal<T>{
public void eat(T t){
System.out.println("eat = " + t);
}
@Override
public void play(T t) {
System.out.println("play = " + t);
}
}
interface Animal<E> {
public void play(E e);
}