What is the main advantage of making a class abstr

2019-01-28 11:11发布

Why do we declare a class as abstract? I know it cannot be instantiated, but why give a special keyword for it. Even a 'normal' class will work just as well and can be easily subclassed. so what is the main advantage of making a class abstract?

9条回答
Root(大扎)
2楼-- · 2019-01-28 11:38

It's useful if you want to have a group of classes that inherit the same logical functions. But in the same time, the class only implements the basic logic, and doesn't contain any real functionality.

You should see it as a skeleton class.

For example, I once made a class with these specifications :

  1. Controls the process of executing a command on another thread, and relays events of that process.

  2. The class itself didn't have any functionality by itself (didn't implement the actual work() function)

So the result is an abstract class, that can be inherited, that already has a built in thread control, which all you need to do is just implement the work() method.

查看更多
趁早两清
3楼-- · 2019-01-28 11:39

An abstract class can have abstract methods and "concrete" methods.

The "concrete" methods can use the abstract methods, and can be sure that they are (correct) impelmented at runtime. Because every (not abstract) subclass has to implement them. (And ther will be no instance of the abstract class itselfe).

So it is all about savety! - It makes sure that the programmer who want to subclass an abstract class must implement the abstract method(s).

If you do this only with a normal class then the class, corresponding to the abstract class, would have the (abstract) methods with an empty Implementation, and only a notic to the programmer that he has to override this method.

Of course you can use the concept of abstract classes for other thinks, like create not instanciable classes, but that is not the main point.

查看更多
虎瘦雄心在
4楼-- · 2019-01-28 11:41

If your class has some default behavior and you want some other behavior to be implemented by the extending classes then you use abstract classes. They cannot be initialized, you can think of abstract classes as a template for the extending classes.

Abstract classes can also call the abstract methods which in result calls extending object's method. Anyways there are lot's of discussions about when to use abstract classes, when to prefer it over an interface. Make a google search, it is an epic discussion :) interfaces vs abstract classes.

查看更多
登录 后发表回答