如何使用接口引用类型访问类实例方法?

huangapple go评论75阅读模式
英文:

How to access class instance method using Interface ref type?

问题

有一个下面的代码片段。

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?是否有特定的方式,以便我们可以使用接口的引用类型访问类的方法?

英文:

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 ?

答案1

得分: 1

正确的方式是在Monster接口上声明doSomething()方法。如果需要在接口类型上调用方法,那么该方法需要存在于接口或其父接口中。

如果无法实现上述方式,那么可以安全地将mon转换为Character.Gorgon

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

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();
 }

huangapple
  • 本文由 发表于 2020年8月8日 15:13:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63312751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定