5

I'm new to java and I'm learning about interfaces and polymorphism. And i want to know what is the best way to do it.

Suppose i have a simple class.

class Object{ // Renders the object to screen public void render(){ } 

I want to give something that object can do, though an interface:

interface Animate{ // Animate the object void animate(); } 

If i want to implement the inteface for animation i can do the following:

class AnimatedObject extends Object implements Animate{ public void animate() { // animates the object } } 

Since all not objects can animate i want to handle the rendering of the animation though polymorphism, but don't know how to diferentiate the objects wihout using InstanceOf and not having to ask if it implemented the interface or not. I plan to put all this objects in a container.

class Example { public static void main(String[] args) { Object obj1= new Object(); Object obj2= new AnimatedObject(); // this is not possible but i would want to know the best way // to handle it do i have to ask for instanceOf of the interface?. // There isn't other way? // obj1.animate(); obj1.render(); obj2.animate(); obj2.render(); } } 
1
  • 1
    You are correct, as long as you want to use inheritance and interface polymorphisms, you'll always need to check if a given subclass/interface is instantiated, then cast to that class and use its implemented method. Since you are learning, look at the answer of @FunctionR - that'll solve your problem Commented Dec 15, 2014 at 6:24

1 Answer 1

4

You are actually closer than you know. In fact you have stumbled on a recurring problem, that can be solved with the Strategy Pattern.

enter image description here

The idea, as defined by Gang of Four is to:

Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour

Sign up to request clarification or add additional context in comments.

2 Comments

Correct way to solve OPs specific problem without polymorphisms and inheritance. A bit more context would be nice. e.g. avoid inheritance/why, use an empty animationStrategy for non-animated objects, give each object its strategy when instantiating ;)
You are right. I can use the "strategy" of each object rendering different from one another through the rendering handler. That way i can call all objects through a single call. I had to visualize approaching the problem in a different way. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.