Vepir
Vepir

Reputation: 602

Java pass class as a variable-type?

I have a package levels and classes level_default, level_hard... which each have some methods like Load();, MoveEvent();, TouchEvent();...

I want to store somehow the selected level class in a variable called lets say myLevel

So that then I can use for example myLevel.Load(); to call the load method from that specific stored level.


So far, I've been using switch loops to call the required method from the selected level.
( ... case "1": levels.level_default.load(); break; case "2": levels.level_hard.load(); ...)

But how can It be done like this so I can just select the level, and use its methods without needing to check all the time what level I'm using to call the method from that level?

Upvotes: 0

Views: 88

Answers (1)

Dan Forbes
Dan Forbes

Reputation: 2824

This sounds like a prime opportunity to make use of polymorphism. I would suggest creating a base class or interface called AbstractLevel, ILevel, etc. Then, you can create however many sub-classes or implementing classes that you need, each one providing their own special definition of the API described by the base. When you go to call the method, you don't have to "think" about using the right one...you'll use the right one by virtue of the fact that it's being called on a polymorphic class. A quick Google search brought me to this article, which you might want to look into.

To really answer your question, though, here is an article that talks about runtime type detection in Java.

Upvotes: 1

Related Questions