..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/>
}
}
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.
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.
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.
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.
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'. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With