自定义泛型1

package com.wangg;

import com.sun.org.apache.xpath.internal.operations.String;

/*
GenericTest 是一个普通的类
GenericTest<E>是一个泛型类
<>里面就是一个参数类型,但是这个类型是什么呢?这个类型现在是不确定的,相当于一个占位
但是现在确定的是这个类型一定是一个引用的数据类型,而不是基本数据类型
*/
public class GenericTest<E>{
  int age;
  String name;
  E sex;
  public void a(E n){

  }
  public void b(E[] m){

  }



}
class Test{
  public static void main(String[] args) {
      //GenericTest进行实例化
      //1.实例化的时候不指定泛型:如果实例化的时候不明确的指定类的泛型,那么认为此泛型为Object类型
      GenericTest g1 = new GenericTest();
      g1.a(6);
      g1.a("王刚");
      g1.b(new Integer[]{1,23,4});
      //2.实例化的时候明确的指定泛型--->推荐
      GenericTest<java.lang.String> g2 = new GenericTest<>();
        g2.sex="男";
        g2.a("fasdfajsldf王刚");
        g2.b(new java.lang.String[]{"w","aw","wa"});


  }

}
class sasdf extends GenericTest<Integer>{

}
class Dome{
  public static void main(String[] args) {
      //指定父类泛型,那么子类就不需要在指定泛型了,可以直接使用
      sasdf a = new sasdf();
      a.a(18);
  }


}
class sasdf2<E> extends GenericTest<E>{
  class Dome02{
      public void main(String[] args) {

      }
  }
}

继承问题

如果继承前指定泛型了,那么使用的时候就不需要指定

 

如果继承前没有指定那么子类也会变成一个泛型,创建对象的时候在定义

posted @ 2021-08-11 14:23  πππ·  阅读(34)  评论(0)    收藏  举报