差异抽象和非抽象方法 [英] difference beteen abstract and non abstract method

查看:101
本文介绍了差异抽象和非抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们使用抽象和非抽象方法?

已实现且未实现的方法?

Why do we use abstract and non abstract method?
Implemened and unimplemened method?

推荐答案

抽象方法(以及property)是一种特殊的虚方法:没有实现,因此它被用作派生类中重写方法的原型。这个特性的目的很简单:表明该方法没有意义,除非它被重写,因此,它的声明类只能用作基类,但不能实例化,因此,它也需要是抽象。



相比之下,您可以使用某些虚拟方法创建抽象类或非抽象类,这些方法可能没有做任何事情,但是有一些实现可以调用。这意味着要覆盖此方法,但并非所有派生类都需要。这种方法通常称为伪抽象。伪抽象概念与语言或平台规则无关(因为任何东西都不需要这样的规则) - 这是一种纯粹的代码设计技术。



-SA
Abstract method (as well as a property) is one special kind virtual method: there is no implementation, so it is used as a prototype for overriding methods in derived classes. The purpose of this feature is simple: to indicate that the method makes no sense unless it is overridden, and, hence, its declared class only can be used as a base class, but cannot be instantiated, therefore, it is also required to be abstract.

In contrast, you can create abstract or non-abstract class with some virtual method which perhaps does not do anything, but there is some implementation which can be called. It means that overriding of this method is intended, but not required for all derived classes. Such method usually called "pseudo-abstract". Pseudo-abstract notion has nothing to do with language or platform rules (because such rules are not needed for anything) — this is a pure code design technique.

—SA


抽象方法是不能在基类中使用任何实现声明的方法:它必须在派生类中实现。



这会强制派生类来实现该方法 - 或者它不会编译。它用于当你知道所有派生类都需要一个函数,但你不知道它们将如何实际实现它。

例如,一个Person类可以添加一个抽象的ChargeForGoods方法,派生类(员工和客户)实现不同:员工获得25%的自动折扣,并从工资中扣除,而客户将开具发票。



An Abstract method is one which cannot be declared in the base class with any implementation: it must be implemented in the derived class.

This forces derived classes to implement the method - or it will not compile. It's used for when you know that all derived classes will need a function, but you have no idea how they will actually implement it.
For example, a Person class may add an abstract ChargeForGoods method, which the derived classes (Employee and Customer) implement differently: the Employee gets an automatic 25% discount, and it is deducted from their wages, while the Customer will be invoiced.

public abstract class Person
   {
   public abstract void ChargeForGoods(Item item);

   public void BuyItem(Person purchaser, Item item)
      {
      purchacer.ChargeForGoods(item);
      }
   }

Person类不需要知道方法是如何实现的,只是它是!

The Person class doesn't need to know how the method is implemented, just that it is!


你通常在抽象基类中使用抽象方法,该抽象基类部分地实现了一个功能,并且需要抽象方法,但该方法的实现可以根据从抽象基类继承的具体类而有所不同。
You usually use an abstract method in an abstract base class that implements a functionality partially and requires the abstract method for that but the implementation of that method can vary depending on the concrete class that inherits from the abstract base class.


这篇关于差异抽象和非抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆