1

I have 2 classes

  • classCurvePath
  • classLinearPath

In these classes I have an items ArrayList.

How can I call a method like:

...
 if (i==1) method(classCurvePath);
 if (i==2) method(classLinearPath);
.. 
 void method(Object class) {
 ArrayList al = class.items;
 }

Do I need an interface? How can I do this? This is not working: "cannot be resolved or not a field"

Carl Manaster
40.5k17 gold badges109 silver badges158 bronze badges
asked Feb 1, 2011 at 22:12
4
  • 9
    Check the syntax highlighting. class is a keyword. Commented Feb 1, 2011 at 22:12
  • 1
    @BalusC you should make that an answer Commented Feb 1, 2011 at 22:14
  • @Jonathan: that would have been an incomplete answer since I had to leave the computer :) Commented Feb 1, 2011 at 22:46
  • @BalusC True. It would not have completely resolved the question. However, it might well have been the stumbling block for OP and identifying it may have been all that was needed. (Editing the answer to expand on it would still have been an option as well) Commented Feb 2, 2011 at 14:10

1 Answer 1

3

Yes you probably want an interface (maybe even an abstract class):

public interface Path {
 List<Item> getItems();
}
public class CurvePath implements Path {
 public List<Item> getItems() {
 //specific implementation for curved path, maybe
 return items;
 }
}
public class LinearPath implements Path {
 public List<Item> getItems() {
 //specific implementation for linear path
 return items;
 }
}
//...
void method(Path clazz) {
 ArrayList<Item> al = clazz.getItems();
}
answered Feb 1, 2011 at 22:14
Sign up to request clarification or add additional context in comments.

4 Comments

@Jonathon: don't know why you deleted your answer; dependency injection is often a good idea in and of itself.
its good, but i want more: Path path = null; if (thepath==0) path=new LinearPath(from, to); if (thepath==1) path=new CurvePath(from, to); this error again..
@lacas: Update your question in a clear manner. I don't understand you.
it was pretty much a mirror of yours and yours was a bit more complete. And a minute earlier than mine.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.