Creating Java Class that can contain one variable of any type

Asymetr :

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{
}
Elliott Frisch :

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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12156&siteId=1