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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5007602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:02:18  来源:igfitidea点击:

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

javaabstractsuper

提问by MarkPflug

..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.

..如果是这样,行为是什么?我在最近查看的一些代码中遇到了这个问题,这让我感到非常困惑。我没有 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/>
    }
}

回答by Jon Skeet

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/>
                        ^

回答by rposcro

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.

当您输入“超级”时。在方法名称之前,你对编译器说:'嘿伙计!调用完全在基类中实现的方法。它实际上不存在,因此无法调用它并且编译器会抱怨。只需删除“超级”。并离开 'foo(arg);' 只要。这将告诉编译器在某些子类中查找实现。

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

回答by Robby Pond

That won't compile. You can't invoke an abstract method.

那不会编译。您不能调用抽象方法。

回答by Isaac Truett

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?"

您确定那来自“工作代码库”吗?

回答by Piyush Sharma

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

抽象方法不能被调用,因为它只是一个声明类型,没有定义就没有意义调用它。因此会出现编译时异常