Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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/>
    }
}
like image 578
MarkPflug Avatar asked Feb 15 '11 18:02

MarkPflug


People also ask

Can we use super for abstract class?

An abstract class can have constructors like the regular class. And, we can access the constructor of an abstract class from the subclass using the super keyword.

Can a superclass be abstract in Java?

In some cases your superclass might actually have a default implementation for the method that subclasses are supposed to override. In that case, you cannot make the method abstract. You can still make the superclass abstract though, even if it contains no abstract methods.

Is it OK to call abstract method from constructor in Java?

It's a very bad practice to call an abstract method from a constructor. Methods called from constructors should always be private or final, to prevent overriding.

Can we override a concrete method in a superclass to declare it abstract?

This can be achieve by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the super-class. Thus, a subclass must override them to provide method definition.


2 Answers

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/>
                        ^
like image 200
Jon Skeet Avatar answered Oct 13 '22 00:10

Jon Skeet


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

like image 41
rposcro Avatar answered Oct 12 '22 23:10

rposcro