We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › dynamic linking of object of different classes
Page Index Toggle Pages: 1
dynamic linking of object of different classes (Read 789 times)
dynamic linking of object of different classes
Nov 27th, 2009, 7:39am
 
Hellow,
Id like something what does a work of pointer to function (like in C or assembler). I know there are no pointers in Java. I think varibale of "object" type is a good solution (I can call it's methods), but I need one variable able to store different classes of object.

More specifically for example: I'd like to paint with different types of brushes which I switch by key pressed.  A very clumbsy way how to do it is:

Code:


circle_brush_class circle_brush = new circle_brush_class();
line_brush_class line_brush = new line_brush_class();

string brush;

void keyPressed(){
 if (key=='a'){brush="circle_brush";}
 if (key=='b'){brush="line_brush";}
}

void draw{
 if (brush=="circle_brush")
   {circle_brush.paint(mouseX,mouseY);}
 if (brush=="line_brush")
   {line_brush.paint(mouseX,mouseY);}
}
 

I want to do it somthing like this

Code:

circle_brush_class circle_brush = new circle_brush_class();
line_brush_class line_brush = new line_brush_class();

object brush;

void keyPressed(){
 if (key=='a'){brush=circle_brush;}
 if (key=='b'){brush=line_brush;}
}

void draw{
brush.paint(mouseX,mouseY);
}
 
Re: dynamic linking of object of different classes
Reply #1 - Nov 27th, 2009, 8:14am
 
If I've understood your needs correctly, you could create a parent class or an interface (what you choose might depend if you want to inherit properties/methods); extend or implement that and then use the parent type when referring to your objects.  In pseudocode:

Code:
class ParentClass {
//...
}

class ChildOne extends ParentClass {
//...
}

class ChildTwo extends ParentClass {
//...
}

ChildOne childInstanceOne = new ChildOne();
ChildTwo childInstanceTwo = new ChildTwo();

ParentClass currentObject = childInstanceOne;

currentObject.callMethod();


I've been getting to grips with this myself lately, but managed to get it working in my drag and drop demo, so you might want to look at that for some working code Wink
Re: dynamic linking of object of different classes
Reply #2 - Nov 27th, 2009, 8:40am
 
What blindfish said...
I will just point to another interesting thread discussing of similar problem (even the subject is similar!): Dynamic casting.
Re: dynamic linking of object of different classes
Reply #3 - Nov 27th, 2009, 1:10pm
 
yes, thats exactly what I asked for, it works nicely. thanks
Page Index Toggle Pages: 1