0

I have a class "Sound", which I'm using for an audio engine. This is a basic sound object that contains nothing more than a file path to an audio file, and a Java Clip object to play that file.

I have a couple child classes to this class. For instance, a LoopSound has special variables and functions to facilitate the sound looping after it finishes. There's also MultiSound which is used for a sound effect that needs to be playing multiple instances at the same time, and has it's own set of variables and functions.

Naturally, there might be a Sound that both wants to Loop, and be multi, so I made LoopingMultiSound.

But then I had a 3rd idea, a Sound that you can apply a waveform to to get oscillating volume.

But that means, if I need a class that's any combination of these 3, I need to create that class. Which means I'd need to manually create all 8 classes. And for each function I want to add, that doubles the subclass count, which is not sustainable.

But I can't just pile all those functions into the original Sound object and just have a boolean saying if that child classes aspects are online or not. That would create a lot of clutter and kinda defeats the purpose of inheritance programming. I mean, there's nothing stopping me, and it's the simplest solution, but it's also the least elegant.

There's got to be a better way. How can I dynamically create grandchild class permutations?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
CSDragon
  • 129
  • 1
  • 10
  • 2
    Why not use composition over inheritance here? – Thiyagu Mar 27 '18 at 09:15
  • What's Composition Over Inheritance? – CSDragon Mar 27 '18 at 09:18
  • 1
    The term is favour composition over inheritance, which means: consider composition first, and only use inheritance when you really need to. – Mark Rotteveel Mar 27 '18 at 09:19
  • You would get plenty of ideas when you just google it. – Thiyagu Mar 27 '18 at 09:20
  • I just googled Java Composition, all I see is posts saying to do it instead of inheritance, not what it actually is or how to make one class composite another :\ Is this a new thing, I never heard it once in college. – CSDragon Mar 27 '18 at 09:23
  • I'm also seeing a lot of stuff where it's just saying, like "a car has an engine, so make engine an object inside of the car class", but like, let's say I make classes like LoopController, MultiController, etc. A Sound object might not always have those, or need those. – CSDragon Mar 27 '18 at 09:27

1 Answers1

0

You should consider composition i.e. writing a wrapper for grouping these features, the below link might be helpful,

Difference between Inheritance and Composition

R.daneel.olivaw
  • 2,681
  • 21
  • 31