Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do abstract methods have to be implemented by the first concrete class, and not one further down the chain?

Tags:

java

oop

I'm curious as to why abstract methods MUST be overridden by the first concrete implementing class, and not one further down the hierarchy change.

I'm not suggesting I want to do this, but I'm curious as to why it has to be the first class

Consider this example

abstract class Upper
{
    abstract void doSomething();
}

class Middle extends Upper
{
    void doSomething()
    {
       // I'm forced to be implemented here
    }
}

abstract class Lower extends Middle
{

}

class Bottom extends Lower
{
    void doSomething()
    {
        // I'm valid, but I'm too far down the hierarchy
    }
}
like image 239
Jimmy Avatar asked Jul 07 '11 16:07

Jimmy


3 Answers

By definition a normal class must implement all abstract methods. If you would declare Middle abstract, then you would not have to implement the methods in Middle.

A normal class can be instantiated, whereas a abstract class cannot. Think about what would happen if you try to call the methods that are not implemented in the class.

like image 75
Leonard Brünings Avatar answered Oct 15 '22 12:10

Leonard Brünings


concrete classes are concrete.
Which means they should be able to be initialized and used.
So, if you don't implement the methods, how would it be properly used ? it will be incomplete and thus not concrete.

You could make another abstract class inherit an abstract class.

like image 40
Yochai Timmer Avatar answered Oct 15 '22 12:10

Yochai Timmer


Just make Middle an abstract class, and it's fine.

If you want to keep Middle as a concrete class but also remove the doSomething from it, please explain what you'd want this code to do:

Upper x = new Middle();
x.doSomething();
like image 4
Jon Skeet Avatar answered Oct 15 '22 14:10

Jon Skeet