1

I'm trying to make a simple little class where I can make something similar to a macro in C/C++. Basically I want to be able to call the following code when I need to perform a few actions though a list of objects, like so:

new IteratableList{
   void action() {
       // do something
   }
}.perform();

I haven't programmed in Java in quite a while, and I can't figure out what is wrong with my code when I try to add the abstract action method:

import java.util.List;
import java.util.Iterator;

public abstract class IteratableList<T> {
    public void perfrom(List<T> ls) {
        Iterator<T> l = ls.iterator();
        while (l.hasNext())
            action(l.next());
    }

    private abstract void action(<T> obj);
}

My code doesn't get any errors until I type that last method. I get errors telling me to remove abstract from the method header, and when I change that I get a list of other errors. I feel like I missed a fundamental thing here. Does any one see a glaring error?

2 Answers 2

7
private abstract void action(<T> obj);

should be

protected abstract void action(T obj);

When you have a generic method you have to define it in the method signature as such:

protected abstract <T> void action(T obj);

unless (and this is the case here) the generic parameter is defined at class level.

You should also remove the private modifier and make it protected instead. abstract indicates the method has to be overridden, but private indicates subclasses can't access it. protected expands the accessibility of private to subclasses.

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

4 Comments

Why was I downvoted? A comment to clarify would be a lot more helpful.
Jeroen - because you can't have a private abstract method. Since (by definition) it would have to be protected or public or package for a subclass to override it. I objected to this line private abstract <T> void action(T obj);.
@ElliottFrisch: that's right underneath it. I focused on the faulty generic assignment rather than the accessor at first. I'll edit it to prevent misunderstandings.
Sorry. I must have missed it the first time.
0

Instead of

private abstract void action(<T> obj);

I think you want

protected abstract void action(T obj);

The syntax for the generic was wrong, and you can't have a private abstract method.

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.