Method call using generics type variables
I have a scenario that I want to create one D support class that contains a generic method. I have set an upper bound for the type variable.
class A{
void show(){
System.out.println("Hello A");
}
}
class B extends A{
void msg(){
System.out.println("Hello B");
}
}
class C extends A{
void msg(){
System.out.println("Hello C");
}
}
class D{
<T extends A> void display(T ob){
ob.msg(); //here i want to do some tricks
}
}
First, I want to share my task. Here the msg () function of class B and C have different implementations. I want to create one D support class that has one display method using display method. I want to call an instance-specific class B or C function msg (). Can you tell me how I can achieve this?
source to share
You need a method msg()
in the class A
, otherwise the method display()
in the class D
doesn't know if this method exists or not in the object you pass to it. (What if someone makes a class E
that extends A
, but doesn't have a method msg()
, and you pass E
in D.display()
?).
If you don't want to inject a method msg()
in a class A
, you can do it abstract
(and you will have to do a class as well abstract
).
abstract class A {
public abstract void msg();
// ...
}
source to share
more like architecture style, I would use an interface for that, so your generic method is constrained <T extends If> void display(T ob)
where If is an interface with an abstract methodmsg
interface If {
void msg();
}
class A {
void show() {
System.out.println("Hello A");
}
}
class B extends A implements If {
@Override
public void msg() {
System.out.println("Hello B");
}
}
class C extends A implements If {
@Override
public void msg() {
System.out.println("Hello C");
}
}
class D {
<T extends If> void display(T ob) {
ob.msg(); // here i want to do some tricks
}
}
source to share
You don't need generics for this, there is a basic concept called dynamic binding in Java.
abstract class A{
void show(){
System.out.println("Hello A");
}
abstract void msg();
}
class B extends A{
@Override
void msg(){
System.out.println("Hello B");
}
}
class C extends A{
@Override
void msg(){
System.out.println("Hello C");
}
}
class D{
void display(A ob){
ob.msg();
}
}
Here, the corresponding instance provided to the method will determine which class method should be called at runtime.
source to share