为什么编译器在这种情况下无法解析实例方法的符号?

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

Why can't the compiler resolve the symbol for instance method in this case?

问题

假设一个类 MyClass 实现了一个接口 MyInterface,并且它有自己的实例方法,比方说是 foo()。
当我像这样创建一个 MyClass 的实例:

MyInterface myClass = new MyClass();

编译器不会允许我在没有显式转换的情况下访问它的实例方法:

myClass.foo();  // 无法解析符号
((MyClass) myClass).foo(); // 这样是可以的

尽管编译器显然知道 myClass 是 MyClass 的一个实例:

if(myClass instanceof MyClass)
  System.out.println(myClass.getClass().getName()); // 这将打印 "MyClass"

为什么我需要使用强制转换,才能让编译器允许我访问这个实例方法呢?

英文:

Suppose a class MyClass implements an interface MyInterface, and it has its own instance method let's say foo().
When i create an instance of MyClass like this:

MyInterface myClass = new MyClass();

The compiler wouldn't let me access its instance method without an explicit casting:

myClass.foo();  // Can't resolve symbol
((MyClass) myClass).foo(); // this is okay

Even though the compiler obviously knows myClass is an instance of MyClass:

if(myClass instanceof MyClass)
  System.out.println(myClass.getClass().getName()); //this will print "MyClass"

Why do i need to use cast for compiler to allow me to access the instance method?

答案1

得分: 2

代码部分不要翻译, 只返回翻译好的部分:

"The meaning of the line MyInterface myClass = new MyClass() is, "Create a new MyClass, and then forget about all its features except those defined in the interface MyInterface."

When you refer to "the compiler obviously knows myClass is an instance of MyClass," you're not actually correct: it's not the compiler that knows that, but the runtime. The compiler was told to forget that information, and it did."

英文:

The meaning of the line MyInterface myClass = new MyClass() is, "Create a new MyClass, and then forget about all its features except those defined in the interface MyInterface."

When you refer to "the compiler obviously knows myClass is an instance of MyClass," you're not actually correct: it's not the compiler that knows that, but the runtime. The compiler was told to forget that information, and it did.

答案2

得分: 0

可能是类型为MyClass,但您将其视为MyInterface。当您执行A myVar = new B();时,您只能访问您可以在A中访问的内容,即使myVar的类型是B

英文:

It might be of type MyClass but you are treating it as a MyInterface. When you do A myVar = new B(); you only have access to whatever you can access in A even though myVaris of type B.

huangapple
  • 本文由 发表于 2020年9月1日 06:22:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63678928.html
匿名

发表评论

匿名网友

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

确定