Override setup?

edited December 2017 in How To...

I want to make many similar classes so I thought the solution would be to make them children of the same class. The thing is, with examples of "extends class", I've only seen child classes overriding methods. All my classes have the same meathods and constructor, but different setup, (they create audio players using different files). How do I override the data of a class?

It'd be really nice to stop having to copy and paste every time I change how these work.

Answers

  • How do I override the data of a class?

    The constructor can take parameters...

  • No need to extend in your case. If they have all the same functionality and different property (different song file name in this case), then you need a single class with a proper constructor as koogs suggested. Check the example below. Notice this is conceptual as I didn't test it. Notice I have to passed a reference to the current PApplet to my class as it is required by the SoundFile's constructor.

    Kf

    import processing.sound.*;
    
    final int N=3;
    
    MyAudioCustomObject[] multipleAudios;
    
    void setup(){
       size(500,500);
       multipleAudios=new MyAudioCustomObject[N];
       multipleAudios[0]=new MyAudioCustomObject(this,"Christmas_song.mp3");
       multipleAudios[1]=new MyAudioCustomObject(this,"Summer_party.mp3");
       multipleAudios[2]=new MyAudioCustomObject(this,"Rocket_man.mp3");
    }
    
    void draw(){
    
    }
    
    void mouseClicked(){
       //Stop all objects
       for(int i=0;i<N;i++)
         multipleAudios[i].stop();  
    
       //Play a random object
       multipleAudios[(int)random(3)].play();
    
    }
    
    
    
    Class MyAudioCustomObject{
      String filename;
      SoundFile audioObj;
      PApplet p;
    
       //Constructor
       MyAudioCustomObject(PApplet pa,String fn){
            p=pa;
            filename=fn;
            initAudio();
       }
    
        void initAudio(){
           audioObj=new SoundFile (p,filename);
        }
    
        void play(){
           println("Playing now: "+filename);
           audio.play();
        }
    
        void stop(){
           audio.stop();
        }
    }
    
Sign In or Register to comment.