java中调用超类的抽象方法是否有效
..如果是的话,行为是什么? 我在最近查看的一些代码中发现了这一点,这让我感到非常困惑。我没有java编译器,所以我自己无法轻易回答这个问题。这是我正在谈论的内容的粗略示例。我预计这个结果会导致编译错误,但据我所知,它来自工作代码库。
abstract class Base {
...
abstract boolean foo(String arg);
}
class Sub extends Base {
...
boolean foo(String arg) {
if(condition)
return true;
else
return super.foo(arg); //<-- <boggle/>
}
}
..and if so what is the behavior?
I came across this in some code I was looking at recently, and it is very confusing to me. I don't have a java compiler, so I can't answer this easily myself. Here is the rough example of what I'm talking about. I would expect this result in a compile error, but as far as I know it is from a working code base.
abstract class Base {
...
abstract boolean foo(String arg);
}
class Sub extends Base {
...
boolean foo(String arg) {
if(condition)
return true;
else
return super.foo(arg); //<-- <boggle/>
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,如果它在超类中是抽象的,你就不能调用它。尝试编译您的代码(已修复其他代码)会出现以下错误:
No, if it's abstract in the superclass you can't call it. Trying to compile your code (having fixed the others) gives this error:
当你输入“超级”时。在方法名称之前,你对编译器说:'嘿伙计!调用完全在基类中实现的方法'。它实际上并不存在,因此无法调用它并且编译器会抱怨。只需删除“超级”即可。并留下'foo(arg);'仅有的。这将告诉编译器在某个子类中寻找实现。
顺便说一句,如果您的示例中的条件始终为假,它将进入不定式循环并因内存不足而崩溃:)
干杯,~r
When you put 'super.' before the method name, you say to compiler: 'hey man! call the method implemented exactly in the Base class'. It doesn't exist there actually so it cannot be called and compiler complains. Just remove 'super.' and leave 'foo(arg);' only. This which will tell the compiler to look for a implementation in some subclass.
BTW, if condition in your example is always false, it'll get into infinitive loop and crash because of out of memory :)
Cheers, ~r
那不会编译。您无法调用抽象方法。
That won't compile. You can't invoke an abstract method.
将您的示例放入 Eclipse 中并对其进行编辑,使其实际上编译到此为止会产生以下错误:
“无法直接调用 Base 类型的抽象方法 foo(String)”
您确定它来自“工作代码库吗?”
Tossing your example into Eclipse and editing it so it actually compiles that far produces this error:
"Cannot directly invoke the abstract method foo(String) for the type Base"
Are you sure that comes from a "working code base?"
抽象方法不能被调用,因为它只是一个声明类型,没有定义就没有必要调用它。这样编译时就会出现异常
Abstract method can't be called as it is just a declaration type, without a definition there is no point calling it. Thus Compile time Exception will occur