This site requires JavaScript, please enable it in your browser!
Greenfoot back
bonyay
bonyay wrote ...

2026/5/31

get random subclass?

bonyay bonyay

2026/5/31

#
this might seem stupid, but I was wondering if there was any way to get a random subclass? like, say i had a subclass of actor and then 3 subclasses of that subclass, and i wanted to select a random one of those 3 to display on the screen. is that possible? like how there's Greenfoot.getRandomNumber(), but for subclasses?
danpost danpost

2026/6/1

#
bonyay wrote...
I was wondering if there was any way to get a random subclass? like, say i had a subclass of actor and then 3 subclasses of that subclass, and i wanted to select a random one of those 3 to display on the screen. is that possible?
Here is an example method using mock class names. The return type can be modified to be the parent class name.
private ParentClassName getRandomParentClassNameActor() {
    ParentClassName actor = null;
    switch(Greenfoot.getRandomNumber(3)) {
        case 0:  actor = new SubclassA(); break;
        case 1:  actor = new SubclassB(); break;
        case 2:  actor = new SubclassC(); break;
    }
    return actor;
 }
You need to login to post a reply.