Do I correctly understand what a class is?

前端 未结 9 856
Happy的楠姐
Happy的楠姐 2021-01-01 20:52

I\'ve had trouble finding a clear, concise laymans definition of a class. Usually, they give general ideas without specifically spelling it out, and I\'m wondering if I\'m u

9条回答
  •  有刺的猬
    2021-01-01 21:47

    A class is a kind of thing, an object is an actual thing. So, in the real world, "person" is a class, you and I are objects (or instances) of that class. "Car" is a class, my 1996 beater Volvo station wagon is an object.

    Objects all have certain similarities in form and function because of the class they belong to. When I say my station wagon is a "car", you have a pretty good idea of what it looks like, what it's used for, and what it can do. But objects of a class can also differ from each other. Just because something's a car doesn't tell you exactly what shape it is or how many seats it has or what color it is.

    In the example you gave, it's likely that the yes and no buttons are both objects of the class "button" (or some similar name) and that the differences in their behavior are due to changes added by the programmer without his or her bothering to create a new class. However, it is possible that the programmer made the decision to make each type of button a subclass of the original class "button".

    What's a subclass? Well, if you think of "car" as a class, it is obvious that there are several intermediate "kinds" of things between "car" and "Larry's 1996 beater Volvo station wagon". These could be "station wagon" and "Volvo station wagon". So my car would be an instance of "Volvo station wagon" which itself would be subclass of "station wagon" which would be a subclass of "car". From the "car" part, we know a good deal about my object, from the "station wagon" part we learn a little more, and from the "Volvo station wagon" a little more still.

    The way in which classes and subclasses are arranged is a decision made by the programmer. In my example above, another programmer might have made the classes "car", "Volvos", "pre-Ford", and "Wagons". It depends on the problem you're trying to solve.

提交回复
热议问题