0

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.

J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Michael Staples
  • 177
  • 2
  • 16
  • 1
    Possible duplicate of [Casting objects in Java](http://stackoverflow.com/questions/5306835/casting-objects-in-java) – rbp Jan 15 '16 at 20:35
  • Yes, [downcasting](http://stackoverflow.com/a/380828/1810429). – J0e3gan Jan 15 '16 at 20:40

1 Answers1

0

you need to instantiate it based on the classname:

  Class cc = Class.forName(advCommand); 
  Circle c = (Circle)c.newInstance();
  c.changeSize(reader.convertToInt(perCommand));
rbp
  • 1,850
  • 15
  • 28
  • You Genius Man! Thank you so much this works however the code is a little different as you have to get the object from the hashmap, I had no idea you had to cast it, if possible could you explain casting something in more detail and what it does exactly? ` ((Circle) objectName.get(advCommand)).changeSize(reader.convertToInt(perCommand));` – Michael Staples Jan 15 '16 at 20:41
  • yes, try this: https://howtoprogramwithjava.com/java-cast/ . would appreciate an upvote + correct answer check! – rbp Jan 15 '16 at 20:44