Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 object arguments must be from the same class

Tags:

java

I want to create a method where 2 or more Object parameters have to be passed, that have to be from the same class.
Object foo and bar have to be members of the same class.

public void method(Object foo, Object bar) {
}

I remember that I have seen something like this before, but I cant remember how it was done exactly.

public void method(Object<?> foo, Object<?> bar) {
}
like image 216
Busti Avatar asked Mar 13 '23 14:03

Busti


1 Answers

I think you mean something like this:

public <T> void method(T foo, T bar) {
}

Here you define the generic type T without any bounds and require the parameters to both be of type T (or a subclass). Then you can call it like this:

method("string1", "string2"); //ok
method(Integer.valueOf(1), Long.valueOf(1) ); //works, Compiler will infer T = Number
this.<Integer>method(Integer.valueOf(1), Long.valueOf(1) ); //You set T = Integer, so the compiler will complain
like image 170
Thomas Avatar answered Mar 23 '23 14:03

Thomas