why do we need abstract classes in Java? [closed]

随声附和 提交于 2019-11-28 08:21:37
Scary Wombat

An abstract class can be used as a type of template for other classes. The abstract class will hold common functionality for all classes that extend it.

For example:

Abstract Class Animal 

All animals move and breathe and reproduce so these can be put into the Animal Class.

Now

 Concrete Class Dog, Cat etc.

Have these base functions already provided.

Abstract classes permit providing a partial set of default implementations of methods in a class. Since they're incomplete, they can't be instantiated and used as they stand, but they can be subclassed to add the missing details in a way that's specific to that particular implementations, and those subclasses can be instantiated.

Without abstract classes, you would have to provide dummy implementations of the methods you intend to override ... which could be done, but then there'd be the risk of forgetting to implement one of them. Having some methods remain entirely abstract ensures that the real implementations have to fill in the gaps, or continue to be abstract themselves and force their descendents to do so.

It's not something the language couldn't live without. But it's Very Useful. You'll discover just how useful as you become more proficient in Java and OO design.

(Note that we said the same thing, basically, last time you brought up this question. So if you're still confused, you might want to be more specific about exactly what's confusing you.)

The are many uses of abstract clasees, the main purpose of abstract classes is to function as base classes which can be extended by subclasses to create a full implementation.

For example,

You may have three steps to be implemented in your program,

  • Few steps before the action
  • Some action to be performed
  • Few steps after the action

So in this case you can define an abstract class with the three methods like this:

public abstract MyAbstractProcess {
    public void stepBefore() {
        //implementation directly in abstract superclass
    }

    public abstract void action(); // implemented by subclasses

    public void stepAfter() {
        //implementation directly in abstract superclass
    }
}

Also, the above example of abstract class Animal is also a very good example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!