简体   繁体   English

如果无法创建抽象类的新对象,那么在抽象类中使用非抽象方法有什么意义呢?

[英]What is the point of having non abstract methods in the abstract class if a new object of the abstract class can't be created?

An abstract class can have both abstract and non abstract methods. 抽象类可以同时具有抽象和非抽象方法。 What is the point of having non abstract methods in the abstract class if a new object of the abstract class can't be created? 如果无法创建抽象类的新对象,那么在抽象类中使用非抽象方法有什么意义呢?

I know you can override the non-abstract method in a child class and then use it through the object of the child class. 我知道你可以覆盖子类中的非抽象方法,然后通过子类的对象使用它。 But if you are doing that, what is the need of having the non-abstract method with an implementation in the first place? 但是如果你这样做,那么首先需要使用非抽象方法和实现是什么?

Think more or google more. 想想更多或谷歌更多。

  1. If your child classes have the common functionality then why you will override the method in every class? 如果您的子类具有通用功能,那么为什么要覆盖每个类中的方法? you can use the base class(which is abstract in this case) method.There comes the need of non-abtract(concrete as they called mostly) methods. 你可以使用基类(在这种情况下是抽象的)方法。需要非abtract(具体,因为他们主要调用)方法。
  2. while having abstract method there(as you know already i think), we can override according to our requirement. 在那里有抽象方法(你已经知道我认为),我们可以根据我们的要求覆盖。
  3. If you need all methods should be override in every child classes according to their requirement, then you can go for Interface. 如果你需要所有方法都应该根据他们的要求覆盖每个子类,那么你可以去接口。

Simple answer: Reuse and maintainability. 简单的答案:重用和可维护性。

Suppose there are 4 concrete classes extending your abstract class which are all going to share some behaviors. 假设有4个具体类扩展你的抽象类,它们都将分享一些行为。

In this case it is better to implement the method in abstract class rather than defining it separately in all your concrete classes. 在这种情况下,最好在抽象类中实现该方法,而不是在所有具体类中单独定义它。

Concrete subclasses can use methods in the abstract superclass. 具体的子类可以使用抽象超类中的方法。 So all shared functionality between subclasses can go into the base abstract class. 因此,子类之间的所有共享功能都可以进入基本抽象类。

Code reusage. 代码重用。 If you don't override non-abstract methods in your inheriting class(es) you inherit them from the abstract class. 如果不覆盖继承类中的非抽象方法,则从抽象类继承它们。

相反,将它们放在子类中违反了DRY的原则(不要重复自己):如果所有子类具有相同的功能,为什么要在每个类中重复写入它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM