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