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

Java 继承泛型类和实现泛型接口_第1张图片

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



public class Test{

	public static void main(String[] args) {
	  
	  
	}
}
class Father{
	
}
interface ARB{
	
}
class child extends Father implements ARB{
	
}

泛型继承的四种情况

  • 全部继承

子类泛型可以比父类多



public class Test{

	public static void main(String[] args) {
	  Father father = new child<>(1, "2");
	  child child = new child<>("1","2");
	  
	}
}
class Father{
	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 extends Father {

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

 

  • 部分继承

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



public class Test{

	public static void main(String[] args) {
	  Father father = new child<>(1, "2");
	  child child = new child<>("1","2");
	  
	}
}
class Father{
	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 extends Father {//继承时将父类一个泛型实例化

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

 

实现父类泛型

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



public class Test{

	public static void main(String[] args) {
	  child child = new child<>(1,"2");
         //无论怎么写第一个都是整形,第二个是字符串
	  
	}
}
class Father{
	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 extends Father {

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

 

不实现父类泛型 

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



public class Test{

	public static void main(String[] args) {
	  child child = new child<>("1","2");
	  
	}
}
class Father{
	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 extends Father{

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


	
}

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(java)