Raj
Raj

Reputation: 3462

Java Generic Calling Method of Variable Type

I have a basic question about generics in Java. I have a class X which is instantiated by another class T. In every class T which will be used has a method called as methodOfT(). However, Java gives me compiler time error since it does not know obj and methodOfT().

public class X<T>
{
     T obj;
     public void methodOfX()
     {
          obj.methodOfT();
     }  
}

In order to avoid this problem, what I did is I defined another class XSuper. And every class now which wants to instantiate X will extend this XSuper class. This removes the compile time error and allows me to achieve what I want.

public abstract class XSuper
{
    public abstract void methodOfT();
}

public class UserOfX extends XSuper
{
    X<UserOfX> objX = new X<UserOfX>();
    public void methodOfT() 
    {
    }
}

However, I want to know the cleaner way of doing this thing. Since I want to derive class UserOfX from another Class. Another Problem is that I want to define methodOfT() method as -

public methodOfT(T objOfT)
{
}

In this case, the above solution fails. Could someone help.

Upvotes: 0

Views: 213

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

public class X<T>
{
     T obj;
     public void methodOfX()
     {
          obj.methodOfT();
     }  
}

The compiler doesn't know what T is so it is evaluated as Object. Object does not have a methodOfT method, so compilation fails. Here's how to solve that:

public interface SomeInterface{
    void methodOfT();
}
public class X<T extends SomeInterface>
{
     T obj;
     public void methodOfX()
     {
          obj.methodOfT();
     }  
}

In this case, the compiler knows that the supplied T will implement the interface SomeInterface and hence have the method methodOfT. (You can also use classes instead of interfaces, but that's less elegant)

Given your additional requirements, we're going t have to change this code some more:

public interface SomeInterface<X>{
    void methodOfT(X object);
}
public class X<T1, T2 extends SomeInterface<T1>>
{
     T1 obj1;
     T2 obj2;
     public void methodOfX()
     {
          obj2.methodOfT(obj1);
     }  
}

Upvotes: 3

Related Questions