首页 > 编程 > Java > 正文

Java中方法名称和泛型相同的用法示例

2019-11-26 08:44:53
字体:
来源:转载
供稿:网友

本文实例讲述了Java中方法名称和泛型相同的用法。分享给大家供大家参考,具体如下:

一 点睛

Java中,方法的名称可以用泛型替代。

二 实战

1 代码

public class SupGent {  public class A<E> {    E t;    public A( E t ) {      this.t = t;    }    public E E() {  //采用了泛型E,碰巧方法名称也是E,只不过不要弄混淆,有点像宏替换      return t;    }  }  public class B<E> extends A<E> {    public B( E t ) {      super(t);    }  }  public static void main( String[] args ) {    B<String> b = (new SupGent()).new B<String>("test");    System.out.println(b.E());  }}

2 运行

test

3 说明

和下面代码等价

public class SupGent {  public class A<E> {    E t;    public A( E t ) {      this.t = t;    }    public E String() {      return t;    }  }  public class B<E> extends A<E> {    public B( E t ) {      super(t);    }  }  public static void main( String[] args ) {    B<String> b = (new SupGent()).new B<String>("test");    System.out.println(b.String());  }}

更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表