Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method that accept only part of classes

Tags:

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.
!!!

like image 564
Michał Herman Avatar asked Dec 21 '12 12:12

Michał Herman


People also ask

How do I restrict a generic type in Java?

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.

What are generic methods generic methods are the methods defined in a 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.

Can you have a generic method in a non-generic class?

Yes, you can define a generic method in a non-generic class in Java.

What is a generic method and when should it be used?

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.


1 Answers

Use an interface and have only A and B implement it.

like image 97
NimChimpsky Avatar answered Sep 30 '22 03:09

NimChimpsky