简体   繁体   English

在java中的超类上调用抽象方法是否有效

[英]Is it valid to call an abstract method on the super class in java

..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. 我没有java编译器,所以我不能轻易回答这个问题。 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/>
    }
}

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: 尝试编译代码(修复其他代码)会出现此错误:

Test.java:13: abstract method foo(String) in Base cannot be accessed directly
            return super.foo(arg); //<-- <boggle/>
                        ^

When you put 'super.' 当你把'超级'。 before the method name, you say to compiler: 'hey man! 在方法名称之前,你对编译器说:'嘿,伙计! call the method implemented exactly in the Base class'. 调用在Base类中完全实现的方法。 It doesn't exist there actually so it cannot be called and compiler complains. 它实际上并不存在,所以无法调用它和编译器抱怨。 Just remove 'super.' 只需删除'超级'。 and leave 'foo(arg);' 离开'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 干杯,~r

That won't compile. 那不会编译。 You can't invoke an abstract method. 您无法调用抽象方法。

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 因此编译时异常将发生

Tossing your example into Eclipse and editing it so it actually compiles that far produces this error: 将您的示例放入Eclipse并对其进行编辑,以便实际编译远远会产生此错误:

"Cannot directly invoke the abstract method foo(String) for the type Base" “无法直接为类型Base调用抽象方法foo(String)”

Are you sure that comes from a "working code base?" 你确定它来自“工作代码库吗?”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM