hidemyname
hidemyname

Reputation: 4287

Why a subclass of the concrete class can be declared abstract, and some of the parent class methods can be overridden and declared abstract?

Usually we declare the subclass of abstract class to be concrete and override the abstract methods to concrete. Does there exist a use for the opposite?

Upvotes: 3

Views: 2895

Answers (2)

In Java each class i derived from Object type. And this is kind of answer, when you create an abstract class form concrete class. You just declare the the implementation is not complete and should be detailed on lower layer of abstraction.

Upvotes: -1

christopher
christopher

Reputation: 27346

One use case that comes to mind..

Imagine you've got a class as follows..

public abstract class Animal {
    // Some stuff.
}

Then you say, okay, now I want a Giraffe class. Giraffe is specific, so there's no need to make it abstract..

public class Giraffe {
    // Some stuff that overrides or uses the Animal behaviour.
}

Now give it some time, when you've got six or seven applications that use your code.

Then, one day when you're bored, you decide to look up Giraffes on Wikipedia, and you find out that in fact, Giraffe is extremely vague! There's spotted Giraffes, Stripy Giraffes, Long legged Giraffes.. and all of these appear in different countries! So what do you do?

  • You could change Giraffe into an abstract class and extend it in a sub class.. but you've already got a lot of applications using your code. Do you instantly render them obsolete and force a mass update?
  • You can create further classes that describe more specific forms of Giraffe, but.. StripyGiraffe isn't specific enough.. unless you can make that class abstract..

So what do you do?

You take the latter option..

public abstract class StripyGiraffe extends Giraffe

And you can continue to extend it..

public class AfricanStripyGiraffe extends StripyGiraffe

That way, the old code works without a hitch, and you're still more than welcome to extend your object hierarchy as much as possible. You can maintain the integrity of your objects by declaring them as abstract when they're not specific enough to be instanciated, and using this method allows the user to still state.

Giraffe geoffrey = new AfricanStripyGiraffe();

Upvotes: 8

Related Questions