0

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?

1
  • "this didnt work" is never enough information. Rather than just describing the problem, you should give a short but complete example demonstrating it, and include the exact error message you got. Commented Mar 19, 2015 at 11:32

2 Answers 2

2

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".

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Jon for the answer. You said you should be able to write abs x = new con1(); abs y = new con2(); x.foo(y); where this should be illegal in my setting. And "public final class Concrete1 extends Abstract<Concrete1>" sounds very redundant to me. But if this the only solution I will take that approach. Thank you :)
@DanielRoss: With the way you described the code in your question, yes. That wouldn't be the case with the code I've provided.
0

The method definition should be the same on con1 and con2:

@override
public abstract void foo(abs i)
{ ...

Here the annotation check that you are really overriding the parent here. Google "inheritance and polymorphism"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.