【问题标题】:How to access class instance method using Interface ref type? [duplicate]如何使用接口引用类型访问类实例方法? [复制]
【发布时间】:2020-08-08 07:13:49
【问题描述】:

有一个下面的代码sn-p。

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
    
        
    }
}

如何使用 mon 访问内部类的 Gorgon 方法 doSomething ?有没有什么具体的方法,让我们可以使用接口的 ref 类型访问类的方法?

【问题讨论】:

  • 我建议你使用你的 IDE 将 Gorgon 解压成一个新的类型……这样以后维护起来会更容易。

标签: java interface


【解决方案1】:

正确的方法是在Monster 接口上声明doSomething() 方法。如果需要在接口类型上调用方法,则该方法需要在接口上或其父级上。

如果这不可行,那么您可以安全地将 mon 转换为 Character.Gorgon

 if  (mon instanceof Character.Gorgon) {
       ((Character.Gorgon) mon).doSomething();
 }

【讨论】:

  • 我可以通过其他方式访问 doSomething 而不进行强制转换并且不添加到界面中吗?
  • 如果我是你,我不会去其他方式钓鱼。我宁愿尝试重新设计架构。投射是您的场景中最明智的方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 2021-05-27
  • 2020-10-03
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多