温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

方法名称与泛型相同怎么在Java中使用

发布时间:2021-01-14 14:51:52 来源:亿速云 阅读:129 作者:Leah 栏目:编程语言

方法名称与泛型相同怎么在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中使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI