java 泛型类 静态方法_JAVA——泛型类和泛型方法(静态方法泛型)

泛型类定义的泛型,在整个类中有效。如果被方法是用,那么

泛型类的对象明确要操作的具体类型后,所有要操作的类型就已经固定了。

为了让不同的方法可以操作不同类型,而且类型还不确定。那么

可以将泛型定义在方法上。

泛型类

class Demo

{

public void show(T t)

{

System.out.println("show: "+t);

}

public void print(T t)

{

System.out.println("show: "+t);

}

}

class GenericDemo4

{

public static void main(String[] args)

{

Demod = new Demo();

d.show(new Integer(4));

Demod1 = new Demo();

d1.print("haha");

}

}

结果:

show: 4

show: haha

泛型方法

class Demo

{

public void show(T t)

{

System.out.println("show: "+t);

}

public void print(Q q)

{

System.out.println("print:"+q);

}

}

class GenericDemo4

{

public static void main(String[] args)

{

Demo d = new Demo();

d.show("hello boy!");

d.print("Alex i love you !");

}

}

结果:

show: hello boy!

print:Alex i love you !

同时定义泛型类和泛型方法

class Demo

{

public void show(T t)

{

System.out.println("show: "+t);

}

public void print(Q q)

{

System.out.println("print:"+q);

}

}

class GenericDemo4

{

public static void main(String[] args)

{

Demo d = new Demo();

d.show("hello boy!");

d.print("Alex i love you !");

d.print(5);

d.print("heiei");

}

}

结果:

show: hello boy!

print:Alex i love you !

print:5

print:heiei

特殊之处:

静态方法不可以访问类上定义的泛型

如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。

class Demo

{

public void show(T t)

{

System.out.println("show: "+t);

}

public void print(Q q)

{

System.out.println("print:"+q);

}

public static void method(W t)

{

System.out.println("method: "+t);

}

}

class GenericDemo4

{

public static void main(String[] args)

{

Demo d = new Demo();

d.show("hello boy!");

d.print("Alex i love you !");

d.print(5);

d.print("heiei");

Demo.method("hihi");

}

}

结果:

show: hello boy!

print:Alex i love you !

print:5

print:heiei

method: hihi

泛型定义在接口上

interface Inter

{

void show(T t);

}

//第一种

class InterImpl implements Inter

{

public void show(String t)

{

System.out.println("show :"+t);

}

}

/*第二种

class InterImplimplements Inter

{

public void show(T t)

{

System.out.println("show :"+t);

}

}

*/

class GenericDemo5

{

public static void main(String[] args)

{

/*

InterImpl i = new InterImpl();

i.show(4);

*/

InterImpl i = new InterImpl();

i.show("haha");

}

}

结果:

show :haha

第一种相对来说就比较死,固定为String类型了。而第二种可以自己定义。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值