Do I correctly understand what a class is?

前端 未结 9 976
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:48

    From the definition of Class at Wikipedia:

    In object-oriented programming, a class is a construct that is used as a blueprint (or template) to create objects of that class. This blueprint describes the state and behavior that the objects of the class all share. An object of a given class is called an instance of the class. The class that contains (and was used to create) that instance can be considered as the type of that object, e.g. an object instance of the "Fruit" class would be of the type "Fruit".

    A class usually represents a noun, such as a person, place or (possibly quite abstract) thing - it is a model of a concept within a computer program. Fundamentally, it encapsulates the state and behavior of the concept it represents. It encapsulates state through data placeholders called attributes (or member variables or instance variables); it encapsulates behavior through reusable sections of code called methods.

    Your understanding of a Class isn't at all incorrect but to make things clear consider the following...

    The Yes and No buttons plus the TextBox are usually specified within a class taking for example code written in C# (Microsoft .NET Framework). Let's name this class MyClass.

    The actions the buttons cause are handled by what are called handlers (methods). You could write your code in such a way that when you click the Yes button something gets written in the TextBox.

    To instantiate MyClass you'd do the following:

    MyClass myClass = new MyClass();
    
    myClass.ButtonYes += new EventHandler(YourMethodForYes);
    myClass.ButtonNo += new EventHandler(YourMethodForNo);
    
    myClass.TextBox.Text = "Yes button was clicked";
    

    Hope you get the idea.

    I wrote usually above because this cenario you described could be implemented in a number of ways. OOP gives you plenty of ways to accomplish the same task.

    Besides the definition of Class I think that reading about Object Oriented Programming (OOP) can help you a lot to understand it even more. Take a look at Fundamental Concepts.

提交回复
热议问题