Java abstract method with generic argument

I have the following situation: There is abstract Class (abs) and two classes which extend from abs (con1 and con2)

Now I want abs to have an abstract function with an argument where the type of the argument has to be the type of the class itself.

I tried the following in the abs class:

public abstract void foo(abs i);

and the following in con1 and con2:

public abstract void foo(con1 i);
public abstract void foo(con1 i);

but this didn't work. What is the general method to solve problems like that?

Jon Skeet
people
quotationmark

No, basically that doesn't implement the method. With the declarations you've got, I should be able to write:

abs x = new con1();
abs y = new con2();
x.foo(y);

It sounds like you want:

public abstract class Abstract<T extends Abstract<T>>
{
    public abstract void foo(T t);
}

Then:

public final class Concrete1 extends Abstract<Concrete1>
{
    @Override public void foo(Concrete1 x) { ... }
}

Note that this doesn't completely enforce it, as you could still write:

public final class Evil extends Abstract<Concrete1>

... but it at least works when everyone's "playing by the rules".

people

See more on this question at Stackoverflow