Suppose I have following class structure:
class Base {}
class A extends Base {}
class B extends Base {}
class C extends Base {}
I want to write method, that accepts instances of A and B but not instances of C.
Can I achieve it in Java?
I know this is not good inheritance situation (A and B should have common parent different from C), but I am only curious is in Java way to handle situation like this.
EDIT:
!!!
I know that better inheritance will resolve problem. I am only curious, if Java have some standard mechanism to solve problem like that.
!!!
Java For Testers Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.
Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.
Yes, you can define a generic method in a non-generic class in Java.
Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used. It is possible to use both generic methods and wildcards in tandem.
Use an interface and have only A
and B
implement it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With