Reputation: 376
Consider this class:
public class A {
public void method_a(){
System.out.println("THIS IS IT");
}
}
I want to use 'method_a' in another function using generic type to get class A. for example:
public class B {
public void calling_this(){
A = new A();
method_b(A);
}
public <T> void method_b(T m){
m.method_a();
}
}
I get error "cannot find symbol" on m.method_a()
.
Is this method possible or is there any thing like equivalent to it?
Upvotes: 0
Views: 64
Reputation: 542
Define your method as
public <T extends A> void method_b(T m){
m.method_a();
}
When do Java generics require <? extends T> instead of <T> and is there any downside of switching?
Upvotes: 3
Reputation: 9566
With generics you can set some restrictions
interface HasMethodA {
void method_a();
}
...
class ... {
<T extends HasMethodA> ... (..., T hasMethodA, ...) {
...
hasMethodA.method_a();
...
}
}
Upvotes: 2