Home > Blockchain >  How do I call a method shared by classes without casting out of the Object superclass first in Java
How do I call a method shared by classes without casting out of the Object superclass first in Java

Time:10-21

I have multiple different classes (Star, Planet, Moon) each with different draw methods, and I would like to be able to call their respective draw() methods with one call, without having to cast them 3 different times.

Object solarObject = solarObjects.get(i);

if (solarObject.getClass() == Star.class)   ((Star)   solarObject).draw(system);
if (solarObject.getClass() == Planet.class) ((Planet) solarObject).draw(system);
if (solarObject.getClass() == Moon.class)   ((Moon)   solarObject).draw(system);

What I wanted to work was this

Object solarObject = solarObjects.get(i);

solarObject.draw(system);

A different attempt I made was this

solarObject.getClass().cast(solarObject).draw(system);

but it gave the error The method draw is undefined for the type


Is there any way to achieve this sort of behaviour in Java?

CodePudding user response:

To achive the same job with uncluttered typecasting, you make the classes a subclass of a common abstract/concret superclass, or have them implement a common interface (whichever fits your project design). This way, you can store whichever subclass object to that interface and call the 'draw()' method on it (regardless of the type of object, since they all implement the same interface).

Code:

public interface CelestialBody {
    void draw();
}

public class Star implements CelestialBody{
    public void draw(){}
}

public class Planet implements CelestialBody{
    public void draw(){}
}

Demo:

public class Driver {
    public static void main(String[] args) {
        CelestialBody solarObject1 = new Star();
        CelestialBody solarObject2 = new Planet();
        if (solarObject1 instanceof CelestialBody)
            solarObject1.draw();
        if (solarObject2 instanceof CelestialBody)
            solarObject2.draw();
    }
}

Notice that when accepting an unknown object, we use the 'instanceof' operator before referencing it (this is to insure that the inputted object is in fact of type 'CelestialBody').

This type of problem is solved through Inheritance. I would encourage you to read more about it.

  • Related