在看到CSDN一位博主 写了一个泛型的例子,实际运行时发现有error,没有声明对象;
对源代码做了小修改:
主要有两种该法:
import javax.swing.SizeRequirements;
public class GenericFruit {
static class Fruit {
private String name;
@Override
public String toString() {
return "fruit";
}
public void setName(string name) {
this.name = name;
}
}
static class Apple extends Fruit {
@Override
public String toString() {
return "apple";
}
}
static class Person {
@Override
public String toString() {
return "Person";
}
}
static class GenerateTest<T> {
public void show_1(T t) {
System.out.println(t.toString());
}
// 在泛型类中声明了一个泛型方法,使用泛型E,这种泛型E可以为任意类型。可以类型与T相同,也可以不同。
// 由于泛型方法在声明的时候会声明泛型<E>,因此即使在泛型类中并未声明泛型,编译器也能够正确识别泛型方法中识别的泛型。
public <E> void show_3(E t) {
System.out.println(t.toString());
}
// 在泛型类中声明了一个泛型方法,使用泛型T,注意这个T是一种全新的类型,可以与泛型类中声明的T不是同一种类型。
public <T> void show_2(T t) {
System.out.println(t.toString());
}
}
public static void main(String[] args) {
// GenericFruit G = new GenericFruit();
// GenericFruit.Apple apple = G.new Apple();
// GenericFruit.Person person = G.new Person();
// static
GenericFruit.Apple apple = new GenericFruit.Apple();
GenericFruit.Person person = new GenericFruit.Person();
GenericFruit.Fruit fruit = new GenericFruit.Fruit();
GenericFruit.GenerateTest<Fruit> generateTest = new GenericFruit.GenerateTest<Fruit>();
GenericFruit.GenerateTest<Person> generateTest1 = new GenericFruit.GenerateTest<Person>();
// apple是Fruit的子类,所以这里可以
generateTest.show_1(apple);
generateTest1.show_1(person); //
// 编译器会报错,因为泛型类型实参指定的是Fruit,而传入的实参类是Person
// generateTest.show_1(fruit);
// generateTest1.show_1(person);
// // 使用这两个方法都可以成功
generateTest.show_2(apple);
generateTest.show_2(person);
// 使用这两个方法也都可以成功
generateTest.show_3(apple);
generateTest.show_3(person);
}
}
第一种: static 方法,作为类本身访问,则不需要在main 函数中去new个爸爸,直接点孩子就行;
前提i傲剑是前面声明的类 都需要加 static 修饰符;
GenericFruit.Apple 声明了apple对象即可;
// static
GenericFruit.Apple apple = new GenericFruit.Apple();
GenericFruit.Person person = new GenericFruit.Person();
GenericFruit.Fruit fruit = new GenericFruit.Fruit();
GenericFruit.GenerateTest<Fruit> generateTest = new GenericFruit.GenerateTest<Fruit>();
GenericFruit.GenerateTest<Person> generateTest1 = new GenericFruit.GenerateTest<Person>();
第二种,常规声明父类:
GenericFruit G = new GenericFruit();
GenericFruit.Apple apple = G.new Apple();
GenericFruit.Person person = G.new Person();
这一行,需要new个爸爸出来,才能见到内部类孩子
GenericFruit G = new GenericFruit();
泛型类show 输出,E ,T 可以泛化参数类型,变得通用,有点像interface的用法;