Search code examples
javainheritancesubclasssuperclass

How can I call a subclass method using a superclass object?


I'm having an issue with my code where I need to call a subclass method using a superclass object. Is there any possible way to do this or a work around? I'm completely stumped and there is no helpful answer for my issue.

    String basicCommand = commands[0];
    String advCommand = commands[1];
    String perCommand = commands[2];
    if (objectName.get(advCommand)instanceof Circle){
        objectName.get(advCommand);
        //.changeSize(reader.convertToInt(perCommand));

advcommand is of type Shape which is a superclass of the class Circle, and the method changesize() is within Circle.

*Data is within a hashmap.


Solution

  • you need to instantiate it based on the classname:

      Class cc = Class.forName(advCommand); 
      Circle c = (Circle)c.newInstance();
      c.changeSize(reader.convertToInt(perCommand));