Creating an infinite number of instances of the same class.

Hi there. First of I am new here so hello. I am working on a bit of code that requires a large number of classes. Is it possible to generate new instances of a class while the program is running? I.e. is it possible too create an infinite number of instances of the same class? I am sure that there is a solution too this problem, how does processing generate particles for example.

Thanks John

Tagged:

Answers

  • Thanks for the reply.

    However i don't think this solves my problem. For Example:

    I declare class as.

    Car_Class Car1,Car2,Car3;

    This means i can only create 3 instances of the Car_Class But what if i need too create 50 cars. typing this manually will be very time and space consuming.

    Also is it possible too create a class within a class?

  • I am working on a bit of code that requires a large number of classes.

    Since a class is a just block of source code you can have as many classes as you can realistically type in the editor ;)

    is it possible too create an infinite number of instances of the same class?

    Think about it. How can you have an infinite number if objects in a finite amount of memory. ;)

  • Thanks Quark. You make a good point about the memory. May be i have over exaggerated the infinite part. In Python it is possible to create an additional instance of a class during run-time of the program, and wanted too know if it was possible in processing, as the number of instances may vary according the the program.

  • typing this manually will be very time and space consuming.

    Look at arrays.

  • Again thanks..

    I will have good read of those links.

    And will probably be back later :)

  • Instances of classes (aka objects) are only created at runtime and this is true for Processing which is based on Java. The number of objects can vary from sketch to sketch or even between executions of the same sketch. It is all determined by your code.

    What is interesting is that new classes can also be created at runtime but that is another story. :)

  • I am now just confused.

  • No one is actually being helpful here.

    Just use an ArrayList.

    class Car {
      float px, py;
      float r;
      Car() {
        px = random(width);
        py = random(height);
        r = random(TWO_PI);
      } 
      void draw() {
        pushMatrix();
        translate(px, py);
        rotate(r);
        rect(-8, -8, 16, 16);
        triangle(5, 0, -3, -3, -3, 3);
        popMatrix();
      }
    }  
    
    ArrayList<Car> cars;
    
    void setup() {
      size(400, 400);
      cars = new ArrayList();
    }
    
    void draw() {
      background(0);
      cars.add( new Car() );
      for ( Car car : cars ) car.draw();
    }
    
  • edited May 2016

    Thanks TfGuy44 that's perfect. I will give that a go and let you know.

Sign In or Register to comment.