定义扩展类A并实现接口B的成员

定义扩展类A并实现接口B的成员

本文介绍了Java - 定义扩展类A并实现接口B的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个必须满足两个条件的变量,我想在定义中设置它们。我知道我可以用单个变量定义任一条件,像以上任何一个例子一样

  private Class 私有变量; //或
私人类变量; //或
私有B变量;

但是有没有办法让变量满足两个条件?



我希望得到类似的东西

  private Class   

但是当我需要调用它或存储时,我找不到任何可以不使用类型转换的方法它的多个副本

解决方案

您可以声明具有多个边界的类型参数,例如:

  public static< T extends A& B个void test(Class< T> clazz)

但是你不能声明一个具有多个边界的变量: / p>

 私人类  

您可以创建 abstract class C ,它扩展了 A 并实现了 B ,所以只需要一个边界。

 抽象类C扩展A implements B {} 


$ b $ p





$ b $私人类< ?扩展C>变量;


I have a variable that must meet two conditions, and I want to set them in the definition

I know that I can define either condition with an individual variable, like in any of these examples

private Class<? extends A> variable; //or
private A variable; //or
private Class<? extends B> variable; //or
private B variable;

But is there a way to have the variable meet both conditions?

I was hoping for something like this

private Class<? extends A implements B> variable;

But I can't find any way to do this without typecasting when I need to call it or storing multiple copies of it

解决方案

You can declare type parameters that have multiple bounds, such as:

public static <T extends A & B> void test(Class<T> clazz)

But you cannot declare a variable that has multiple bounds:

private Class<? extends A & B> variable;  // doesn't work

You can create an abstract class C that extends A and implements B, so that only one bound is required.

abstract class C extends A implements B {}

Then:

private Class<? extends C> variable;

这篇关于Java - 定义扩展类A并实现接口B的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:52