class Demo
{
public<T> void show(T t)
{
System.out.println(t);
}
public<T> void print(T t)
{
System.out.println(t);
}
}
class Demo1<T>
{
public void show(T t)
{
System.out.println(t);
}
public void print(T t)
{
System.out.println(t);
}
}
class Demo3<T>
{
public void show(T t)
{
System.out.println(t);
}
public<T> void print(T t)
{
System.out.println(t);
}
/*public static void method(T t)
{
System.out.println(t);
}*///此定义失败!
public static <T>void method1(T t)
{
System.out.println(t);
}
}
class GenericDemo
{
public static void main(String[] args)
{
/*Demo d=new Demo();
d.show("xxc");
d.print(5);
d.show(110);*/
/*Demo1<String> d=new Demo1<String>();
d.show("aaa");
d.print(5);*/
Demo3<String>d=new Demo3<String>();
d.print("hahaha");
d.print(5);
d.method1(55555);
}
}
1.将泛型定义在类上时,在整个类中都有效,操作对象时必须明确传入的对象是否符合类上定义的泛型。
2.将泛型定义在方法上时,是为了让同一个方法可以操作不同类型。(如上的打印方法)
3.如果在类上和这个类中的方法中同时定义泛型,那么,方法上定义过泛型的可以不跟类走,但是没定义过泛型的方法需要跟类走。
《*特殊之处*》:
1.静态方法不可以访问类上一定的泛型。(因为类上的泛型是必须建立对象才有的,而静态是类一加载到内存就存在的)
2.如果静态方法操作的引用数据类型不确定,可以将泛型定义在方法上。(泛型写在返回值的前面)