简体   繁体   中英

Java - Setting Parameter as Object which both extends one Object and implements an Interface

I was wondering if it was possible to set a parameter to a method as an Object, which must be a extend one class and implement another. Here is an example: Let's say I have a class called ClassA and an interface called MyInterface.

public class ClassA {
    /* code */
}    


public interface MyInterface {
    /* code */
}

Let's say somewhere else there is a class called ClassB, which both extends ClassA and implements MyInterface.

public class ClassB extends ClassA implements MyInterface {
    /* code */
}

I could also have a ClassC, which also extends ClassA and implements MyInterface:

public class ClassC extends ClassA implements MyInterface {
    /* code */
}

My question is this:

Let's say I have a method called method1, and in method1 I want to have a parameter which accepts an Object. Let's say I wanted this Object to either subclass ClassA or actually be ClassA itself. This is easy to do:

 public void method1(ClassA parameter) {

 }

Let's say I also wanted a method2, and in method2 I want to have a parameter which accepts anything which implements MyInterface. Again, this is easy:

 public void method2(MyInterface parameter) {

 }

But what if I wanted a method3, and I wanted to have a parameter which accepts only objects which either subclass ClassA or is ClassA itself, AND implements MyInterface, and so will accept both ClassB and ClassC, but not any class which only extends ClassA, or only implements MyInterface, or neither. Like:

public void method3 ([Something that extends ClassA implements MyInterface] parameter) {
  /* code */
}

You can do the following:

public <A extends ClassA & MyInterface> void method3(A parameter) { ... }

But I don't think it's a good idea - if you have a concept of object that extends ClassA and implements MyInterface , it would be better to create a separate class or interface to represent that concept.

From your description, it seems as if you require another type of Object. One that both extends ClassA and implements MyInterface. Perhaps, even, this is an abstract class.

I would then use this new object as the parameter type for method3.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM