Why do we need abstract classes in Java? If you're never going to make it into an object, why have it in the first place? How do you use it? Why is it there? I'm wondering the same thing with abstract methods. I find it seems like a similar concept to having a super class with NO subclasses that could ever matter to be made.
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.
来源:https://stackoverflow.com/questions/22085985/why-do-we-need-abstract-classes-in-java