C # abstract class for objects of the abstract method

           First, the abstract class

1.1, the syntax:

It is the abstract class with abstract modified class.

An abstract class may contain abstract members (methods, properties) which are in common [ may be empty, you can not have abstract members, can have abstract members ]

An abstract class can not create object [can not be instantiated, not New]  can be inherited! You can create an array

definition:

transfer:

1.2, semantics (learn):

Abstract class represents an abstraction (data and behavior as a whole).

The concept of co-expression has sex data.

Abstract only said what to do with what data, but often do not express specific practices, did not express specific data values

Used to make the base class, unifying all subclasses, management sub-class .

transfer:

1.3, when used for abstract classes

  1. "I hope to do a base class, class unified management of multiple classes Jiangzai [classification]
  2. " Simply using the abstract class reasons (also when to use abstract methods) :

When looking to find a role when common requirements analysis, to find commonality in there field; there are ways,

Methods Some methods / some behavior , different concrete subclasses may implement different, the parent class is not necessary to achieve this behavior! !

This behavior requires written in the abstract, so this class should become an abstract class.

                   Second, the abstract method

1 "is defined: Only the statement Definitions The method is not implemented abstract methods.

2》特点:实现类必须实现所有的抽象方法  B:A;  抽象方法必须放在抽象类中或者接口中。

      但是子类也是抽象,父类的抽象方法不实现可以吗?可以。

             

3》 放在抽象中的抽象方法 必须 加abstract 不能私有

  实现类实现抽象方法的方法 必须 override 不能私有

 抽象方法的重写 =抽象方法的实现

抽象方法只做什么,但往往不表达具体做法

注意:抽象类 抽象方法,子类 实现为虚方法 不可以

                             

                           三、比较抽象方法与虚方法

下面左边基类是利用抽象方法,右边基类是用的虚方法分别计算圆、三角形、矩形的面积:

调用一样:

那什么时候用抽象方法?什么时候用虚方法呢?

上面图片的代码也是面向对象设计原则之一:氏替换原则 (继承后的重写)

出现地方可以被子类替换掉,要保护替换前的原有的工作,在替换后依然保持不变子类在重写父类方法时,尽量选择扩展重写

但是对于求面积的案例来说用抽象方法比较好,因为父类中的方法子类都没有用到。

抽象方法和虚方法区别:

           从定义来说:抽象方法:只有声明【定义】,没有实现的方法 就是抽象方法;虚方法:用vritual关键修饰的已经实现的方法

            语法说:  抽象方法:实现类必须实现【重写】;虚方法:可以重写也可以不重写

 

发布了122 篇原创文章 · 获赞 13 · 访问量 2万+

Guess you like

Origin blog.csdn.net/qq_40229737/article/details/104009527