首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java 继承泛型类和实现泛型接口

Java 继承泛型类和实现泛型接口

作者头像
用户2965768
发布2019-03-08 10:55:33
6.4K0
发布2019-03-08 10:55:33
举报
文章被收录于专栏:wymwym

泛型也可以继承和实现接口

public class Test{

	public static void main(String[] args) {
	  
	  
	}
}
class Father<T>{
	
}
interface ARB<E>{
	
}
class child<T,E> extends Father<T> implements ARB<E>{
	
}

泛型继承的四种情况

  • 全部继承

子类泛型可以比父类多

public class Test{

	public static void main(String[] args) {
	  Father<Integer,String> father = new child<>(1, "2");
	  child<String,String ,Boolean> child = new child<>("1","2");
	  
	}
}
class Father<T1, T2>{
	T1 t1;
	T2 t2;
	
	public Father(T1 t1,T2 t2){
		this.t1 = t1;
		this.t2 = t2;
		System.out.println(this.t1.getClass());
		System.out.println(this.t2.getClass());
	}
	
	
}
class child<T1, T2, T3> extends Father<T1, T2> {

	public child(T1 t1, T2 t2) {
		super(t1, t2);
	}
	
}
  • 部分继承

同样子类泛型也可以比父类多

public class Test{

	public static void main(String[] args) {
	  Father<Integer,String> father = new child<>(1, "2");
	  child<String,String ,Boolean> child = new child<>("1","2");
	  
	}
}
class Father<T1, T2>{
	T1 t1;
	T2 t2;
	
	public Father(T1 t1,T2 t2){
		this.t1 = t1;
		this.t2 = t2;
		System.out.println(this.t1.getClass());
		System.out.println(this.t2.getClass());
	}
	
	
}
class child<T1, T2, T3> extends Father<T1,String> {//继承时将父类一个泛型实例化

	public child(T1 t1, String t2) {
		super(t1, t2);
	}
	
}

实现父类泛型

子类将父类全部实现,子类独有,不再是继承的

public class Test{

	public static void main(String[] args) {
	  child<String,String ,String> child = new child<>(1,"2");
         //无论怎么写第一个都是整形,第二个是字符串
	  
	}
}
class Father<T1, T2>{
	T1 t1;
	T2 t2;
	
	public Father(T1 t1,T2 t2){
		this.t1 = t1;
		this.t2 = t2;
		System.out.println(this.t1.getClass());
		System.out.println(this.t2.getClass());
	}
	
	
}
class child<T1, T2, T3> extends Father<Integer,String> {

	public child(Integer t1, String t2) {
		super(t1, t2);
	}
	
}

不实现父类泛型 

父类所有成员默认为Object类型

public class Test{

	public static void main(String[] args) {
	  child<String,String ,String> child = new child<>("1","2");
	  
	}
}
class Father<T1, T2>{
	T1 t1;
	T2 t2;
	
	public Father(T1 t1,T2 t2){
		this.t1 = t1;
		this.t2 = t2;
		System.out.println(this.t1.getClass());
		System.out.println(this.t2.getClass());
	}
	
	
}
class child<T1, T2, T3> extends Father{

	public child(Object t1, Object t2) {
		super(t1, t2);
		// TODO Auto-generated constructor stub
	}


	
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年02月25日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档