I'd like a real-world type example that illustrates why exactly a Java abstract method cannot exist in a non-abstract class.
I appreciate the reasons why that can't happen - abstract classes forcing implementation of any abstract methods contained in them - but an understandable concrete example would really help me reason it out in my head, many thanks.
One of the key differences between an abstract class and a non-abstract class is the fact that you cannot create an instance of an abstract class. This prevents a situation where a method with no definition gets called.
So if we had the following abstract class:
abstract class Elephant { // abstract class
public String getName() {
return "Ollie";
}
public abstract void walk(); // abstract method
}
Then the following would be illegal:
Elephant e = new Elephant(); // error
Because Elephant
is abstract and it cannot be instantiated.
But say for argument sake, that we make Elephant
non-abstract but it is allowed to still have the abstract method walk()
. i.e. we change the definition of Elephant
to:
class Elephant { // non-abstract class
public String getName() {
return "Ollie";
}
public abstract void walk(); // abstract method
}
Now what should happen if I do the following:
Elephant e = new Elephant(); // legal since Elephant is non-abstract
e.walk(); // oops, we didn't define this anywhere
Java compiler won't allow this. You could argue that there are other ways to handle a situation like this, but this simply how the Java language has decided to implement the feature.