We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello! I'm relatively new to Processing and OOP.
I'm currently developing a shoot'em'up and I'm using Arraylists to 'control' my enemies. So far, everything has been working fine. I'm starting to get problems when I try to mix different sub-classes in the same arraylist. I can access the methods of all my childs, but I keep getting the fields of my parent.
I've done a fair amount of research, but without success: for clarity's sake, instead of posting my code that is quite lengthy, here's an example of what I'm trying to achieve:
ArrayList shapes = new ArrayList();
void setup() {
shapes.add(new Rect());
shapes.add(new Circle());
for(Shape s : shapes) {
if(s instanceof Rect) {
println("type is rect");
s.show();
println("my ID is: "+s.ID);
}
else if (s instanceof Circle) {
println("type is circle");
s.display();
println("my ID is: "+s.ID);
}
}
}
class Rect extends Shape {
String ID="I'm a rectangle";
void show(){
rect(5,5,10,10);
}
}
class Circle extends Shape {
String ID="I'm a circle";
void display(){
ellipseMode(CORNER);
ellipse(20,5,10,10);
}
}
class Shape {
String ID="I'm nothing";
void display(){};
void show(){};
}
So, 2 questions:
1) how can I access the ID value of my subclass? I keep reaching for its parent value? I'm obviously missing something important... 2) I've read that using 'instanceof' is a bad bad thing: can someone explain why, and what I should do instead?
Thanks by advance!
Answers
The above code gives me ID's of subclasses:
The parent ID should be accessed with
println("my ID is: "+s.super.ID);. Or didn't I get your question?https://forum.Processing.org/two/discussion/13616/inheritance-in-a-class-with-an-array-loop
Alter: the code I posted shouldn't work - I've asked around and realized that my ID redefinition was local to my class...the proper way (that works) is
class Rect extends Shape { Rect (){ ID="I'm a rectangle"; } void show(){ rect(5,5,10,10); } }GotToLoop: thanks, awesome link - this is very close to what I'm attempting!