第一节 泛型引入
定义:使用泛型可以指代任意对象类型
public class C1 {
private Integer a;
public C1(Integer a){
super();
this.a=a;
}
public int getC1(){
return a;
}
public void setC1(Integer a){
this.a=a;
}
public void print(){
System.out.println("a的类型是:"+a.getClass().getName());
}
}
》》》》》》》》》》》
public class C2 {
private String a;
public C2(String a){
super();
this.a=a;
}
public String getC2(){
return a;
}
public void setC2(String a){
this.a=a;
}
public void print(){
System.out.println("a的类型是:"+a.getClass().getName());
}
}
》》》》》》》》》》》》》
public class C3 {
private Object object;
public void setObject(Object object){
this.object=object;
}
public Object getObject(){
return object;
}
public C3(Object object){
super();
this.object=object;
}
public void print(){
System.out.println("object的类型是:"+object.getClass().getName());
}
}
》》》》》》》》》》》》》
public class CC<T> {
//定义泛型
private T obj;
public T getObj(){
return obj;
}
public void setObj(){
this.obj=obj;
}
public CC(T obj){
super();
this.obj=obj;
}
public void print(){
System.out.println("T的类型为:"+obj.getClass().getName());
}
}
》》》》》》》》》》》》》》》
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
C1 c1=new C1(1);
c1.print();
C2 c2=new C2("1");
c2.print();
C3 c31=new C3(1);
int i31=(Integer)c31.getObject();
System.out.println(i31);
C3 c32=new C3("2");
String s32=(String)c32.getObject();
System.out.println(s32);
c31.print();
c32.print();
CC<Integer> cc=new CC<Integer>(1);
cc.print();
int icc=cc.getObj();
System.out.println(icc);
CC<String> cc1=new CC<String>("12");
cc1.print();
int icc1=cc.getObj();
System.out.println(icc1);
}
}
第二节 限制泛型
public class Animal {
public void print(){
System.out.println("animal");
}
}
》》》》》》》》
public class Cat extends Animal{
public void print(){
System.out.println("Cat");
}
}
》》》》》》》》》
public class Dog extends Animal{
public void print(){
System.out.println("Dog");
}
}
》》》》》》》》》》
public class Demo <T extends Animal>{
private T ob;
public T getOb(){
return ob;
}
public void setOb(T ob){
this.ob=ob;
}
public Demo(T ob){
super();
this.ob=ob;
}
public void print(){
System.out.println("ob的类型是:"+ob.getClass().getName());
}
}
》》》》》》》》》
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Demo<Dog> demo=new Demo<Dog>(new Dog());
Dog dog=demo.getOb();
dog.print();
Demo<Cat> demo2=new Demo<Cat>(new Cat());
Cat cat=demo2.getOb();
cat.print();
//Demo<Integer> demo3=new Demo<Integer>; //会报错
}
}
第三节 通配符泛型
public class Test2 {
private static void take(Demo<?> a){
a.print();
}
public static void main(String args[]){
Demo<Dog> demo1=new Demo<Dog>(new Dog());
take(demo1);
Demo<Cat> demo2=new Demo<Cat>(new Cat());
take(demo2);
}
}
第四节 泛型方法
public class Test3 {
private static <T> void f(T t){
System.out.println("T的类型是:"+t.getClass().getName());
}
public static void main(String args[]){
f("");
f(1);
f(2.3);
f(2.3f);
f(new Object());
}
}