What's the difference between abstraction and generalization?

后端 未结 8 1257
滥情空心
滥情空心 2021-01-30 13:26

I understand that abstraction is about taking something more concrete and making it more abstract. That something may be either a data structure or a procedure. For example:

8条回答
  •  萌比男神i
    2021-01-30 14:03

    I'm going to use some examples to describe generalisation and abstraction, and I'm going to refer to this article.

    To my knowledge, there is no official source for the definition of abstraction and generalisation in the programming domain (Wikipedia is probably the closest you'll get to an official definition in my opinion), so I've instead used an article which I deem credible.

    Generalization

    The article states that:

    "The concept of generalization in OOP means that an object encapsulates common state and behavior for a category of objects."

    So for example, if you apply generalisation to shapes, then the common properties for all types of shape are area and perimeter.

    Hence a generalised shape (e.g. Shape) and specialisations of it (e.g. a Circle), can be represented in classes as follows (note that this image has been taken from the aforementioned article)

    enter image description here

    Similarly, if you were working in the domain of jet aircraft, you could have a Jet as a generalisation, which would have a wingspan property. A specialisation of a Jet could be a FighterJet, which would inherit the wingspan property and would have its own property unique to fighter jets e.g. NumberOfMissiles.

    Abstraction

    The article defines abstraction as:

    "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel)"

    In the domain of programming:

    An abstract class is a parent class that allows inheritance but can never be instantiated.

    Hence in the example given in the Generalization section above, a Shape is abstract as:

    In the real world, you never calculate the area or perimeter of a generic shape, you must know what kind of geometric shape you have because each shape (eg. square, circle, rectangle, etc.) has its own area and perimeter formulas.

    However, as well as being abstract a shape is also a generalisation (because it "encapsulates common state and behavior for a category of objects" where in this case the objects are shapes).

    Going back to the example I gave about Jets and FighterJets, a Jet is not abstract as a concrete instance of a Jet is feasible, as one can exist in the real world, unlike a shape i.e. in the real world you cant hold a shape you hold an instance of a shape e.g. a cube. So in the aircraft example, a Jet is not abstract, it is a generalisation as it is possible to have a "concrete" instance of a jet.

提交回复
热议问题