Reputation: 187
I'm making a scene class for which I'd like a not yet defined variable type.
class Scene {
int fps = 60;
float duration;
// one instance of any variable type (another class)
}
as sometimes I'd like the scene to be constructed using :
class Scene {
int fps = 60;
float duration;
Simulation1 simulation;
}
and other times I'd like the scene to be constructed using
class Scene {
int fps = 60;
float duration;
Simulation2 simulation;
}
Simulation1 and Simulation2 are both two very different custom classes but they have some function names in common. For example they both have functions called init(), deleteRandomParticles() and more. Which means that in my main code I can call :
scene.simulation.init();
scene.simulation.deleteRandomParticles();
I find this very practical, but I can't find a way to make the scene class work this way.
full solution :
class Scene<T extends SceneInterface> {
T simulation;
Scene(T simulation) {
this.simulation = simulation;
}
}
interface SceneInterface {
public void init();
public void deleteRandomParticles();
}
and make sure to have this in your simulation classes :
class Simulation1 implements SceneInterface{
}
Upvotes: 1
Views: 74
Reputation: 21
It seems like you're looking for generics, which is the thing that goes in the angular brackets in something like List<String>
. Also, if your simulation classes have methods in common I would make a simulation interface and have simulation 1 and 2 implement it. You can make generics extend an interface like this: class Scene<T extends Simulation>
Then use type T as if it were a variable type like String.
Upvotes: 1
Reputation: 201399
Option 1: Object
.
class Scene {
int fps = 60;
float duration;
Object simulation;
}
Option 2: A Simulation
interface that Simulation1
and Simulation2
both implement.
class Scene {
int fps = 60;
float duration;
ISimulation simulation;
}
Option 3: A generic type T
class Scene<T> {
int fps = 60;
float duration;
T simulation;
}
Upvotes: 3