Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphism and Interfaces in Java

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();

 }
}
like image 606
Sebastián Echeverry Avatar asked Sep 29 '22 05:09

Sebastián Echeverry


1 Answers

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

like image 52
apxcode Avatar answered Oct 04 '22 02:10

apxcode