0

Have a below code snippet.

public class Character {
    private static String type;
    
    public void doMainSomething() {
        System.out.println("Doing Main Something");
    }
    
    public static class Gorgon extends Character implements Monster {
        
        public int level;
        
        @Override
        public int getLevel() { return level; }

        public Gorgon() {
            Character.type = "Gorgon";
        }
        
        public void doSomething() {
            System.out.println("Doing Something");
        }
    }
    
    public static void main(String[] args) {
        
        Character.Gorgon gor = new Character.Gorgon();
        Monster mon = new Character.Gorgon();
        mon.doSomething();  -> Error
    
        
    }
}

How can I access inner class's Gorgon method doSomething using mon ? Is there any specific way, so that we could access class's method using Interface's ref type ?

Jenny
  • 47
  • 6

1 Answers1

1

Proper way is to declare the doSomething() method on Monster interface. If a method needs to be called on interface type, then that method needs to be on the interface or it's parent.

If that is not doable, then you can safely cast the mon to Character.Gorgon

 if  (mon instanceof Character.Gorgon) {
       ((Character.Gorgon) mon).doSomething();
 }
THe_strOX
  • 687
  • 1
  • 5
  • 16
  • any other way I could access doSomething without cast and not adding into interface ? – Jenny Aug 08 '20 at 08:28
  • If I were you I would not go about fishing for other ways. I would rather try to redesign the architecture. Casting is the most sane way for your scenario. – THe_strOX Aug 08 '20 at 08:44