英文:
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();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论