Java – can you request multiple types at once?

Basically, I want to do this:

public interface A {
    void a();
}
public interface B {
    void b();
}
public class SomeClass {
    public SomeClass(<A&B> e) { // Note the type here
        e.a();
        e.b();
    }
}

What I did on the comment line is obviously illegal I know that I only need to pass the object to implement interface a or interface B, but are there two ways to do it?

I think there are some solutions (such as requiring the parameter to be class A, and then checking whether it is also an instance of B), but I won't get the help of the compiler Do you know what to do? Or a smarter solution

Solution

You can do this with generics enabled For example, to accept an instance of a class that implements charsequence and appendable:

public <T extends CharSequence & Appendable> void someMethod(T param) {
    ...
  }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>