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
lacas
14.1k32 gold badges114 silver badges185 bronze badges
1 Answer 1
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
Mark Peters
81.3k17 gold badges164 silver badges196 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Mark Peters
@Jonathon: don't know why you deleted your answer; dependency injection is often a good idea in and of itself.
lacas
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..
Mark Peters
@lacas: Update your question in a clear manner. I don't understand you.
Jonathon Faust
it was pretty much a mirror of yours and yours was a bit more complete. And a minute earlier than mine.
lang-java
classis a keyword.