Questions tagged [class]

A template for creating new objects that describes the common state(s) and behavior(s). NOT TO BE CONFUSED WITH HTML CLASSES OR CSS CLASS SELECTORS. Use [html] or [css] instead.

Not to be confused with HTML classes or CSS class selectors. Use or instead.


In object-oriented programming (see: ), a class is a construct that is used as a blueprint (or a 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 or fields); it encapsulates behavior through reusable sections of code called methods.

More technically, a class is a cohesive package that consists of a particular kind of metadata. A class has both an interface and a structure. The interface describes how to interact with the class and its instances using methods, while the structure describes how the data is partitioned into attributes within an instance. A class may also have a representation (metaobject) at runtime, which provides runtime support for manipulating the class-related metadata. In object-oriented design, a class is the most specific type of an object in relation to a specific layer.

Example of class declaration in C#:

/// <summary>
/// Class which objects will say "Hello" to any target :)
/// </summary>
class HelloAnything
{
    /// <summary>
    /// Target for "Hello". Private attribute that will be set only once
    ////when object is created. Only objects of this class can access
    /// their own target attribute.
    /// </summary>
    private readonly string target;

    /// <summary>
    /// Constructor. Code that will execute when instance of class is created.
    /// </summary>
    /// <param name="target">Target for "Hello". If nothing specified then
    /// will be used default value "World".</param>
    public HelloAnything(string target = "World")
    {
        //Save value in the inner attribute for using in the future.
        this.target = target;
    }

    /// <summary>
    /// Returns phrase with greeting to the specified target.
    /// </summary>
    /// <returns>Text of greeting.</returns>
    public string SayHello()
    {
        return "Hello, " + target + "!";
    }
}

Using an example of the defined class:

class Program
{
    static void Main(string[] args)
    {
        //Say hello to the specified target.
        HelloAnything greeting = new HelloAnything("Stack Overflow");
        Console.WriteLine(greeting.SayHello());

        //Say hello to the "default" target.
        greeting = new HelloAnything();
        Console.WriteLine(greeting.SayHello());
    }
}

Output result:

Hello, Stack Overflow!
Hello, World!

Computer programs usually model aspects of some real or abstract world (the Domain). Because each class models a concept, classes provide a more natural way to create such models. Each class in the model represents a noun in the domain, and the methods of the class represent verbs that may apply to that noun.

For example in a typical business system, various aspects of the business are modeled, using such classes as Customer, Product, Worker, Invoice, Job, etc. An Invoice may have methods like Create, Print or Send, a Job may be Perform-ed or Cancel-led, etc.

Once the system can model aspects of the business accurately, it can provide users of the system with useful information about those aspects. Classes allow a clear correspondence (mapping) between the model and the domain, making it easier to design, build, modify and understand these models. Classes provide some control over the often challenging complexity of such models.

Classes can accelerate development by reducing redundant program code, testing and bug fixing. If a class has been thoroughly tested and is known to be a 'solid work', it is usually true that using or extending the well-tested class will reduce the number of bugs - as compared to the use of freshly-developed or ad-hoc code - in the final output. In addition, efficient class reuse means that many bugs need to be fixed in only one place when problems are discovered.

Another reason for using classes is to simplify the relationships of interrelated data. Rather than writing code to repeatedly call a graphical user interface (GUI) window drawing subroutine on the terminal screen (as would be typical for structured programming), it is more intuitive. With classes, GUI items that are similar to windows (such as dialog boxes) can simply inherit most of their functionality and data structures from the window class. The programmer then needs only to add code to the dialog class that is unique to its operation. Indeed, GUIs are a very common and useful application of classes, and GUI programming is generally much easier with a good class framework.

Source: Wikipedia.

See also:

79352 questions
741
votes
15 answers

Does Python have “private” variables in classes?

I'm coming from the Java world and reading Bruce Eckels' Python 3 Patterns, Recipes and Idioms. While reading about classes, it goes on to say that in Python there is no need to declare instance variables. You just use them in the constructor, and…
Omnipresent
  • 29,434
  • 47
  • 142
  • 186
706
votes
19 answers

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

I prefer to use OOP in large scale projects like the one I'm working on right now. I need to create several classes in JavaScript but, if I'm not mistaken, there are at least a couple of ways to go about doing that. What would be the syntax and why…
Karim
  • 18,347
  • 13
  • 61
  • 70
690
votes
9 answers

Why is enum class preferred over plain enum?

I heard a few people recommending to use enum classes in C++ because of their type safety. But what does that really mean?
Oleksiy
  • 37,477
  • 22
  • 74
  • 122
672
votes
11 answers

When to use static classes in C#

Here's what MSDN has to say under When to Use Static Classes: static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... } Use…
pbh101
  • 10,203
  • 9
  • 32
  • 31
629
votes
16 answers

Can we instantiate an abstract class?

During one of my interview, I was asked "If we can instantiate an abstract class?" My reply was "No. we can't". But, interviewer told me "Wrong, we can." I argued a bit on this. Then he told me to try this myself at home. abstract class my { …
Ravi
  • 30,829
  • 42
  • 119
  • 173
623
votes
18 answers

Does the 'mutable' keyword have any purpose other than allowing a data member to be modified by a const member function?

A while ago, I came across some code that marked a data member of a class with the mutable keyword. As far as I can see it simply allows you to modify a member in a const-qualified member method: class Foo { private: mutable bool done_; …
Rob
  • 76,700
  • 56
  • 158
  • 197
589
votes
23 answers

When is it appropriate to use C# partial classes?

I was wondering if someone could give me an overview of why I would use them and what advantage I would gain in the process.
Asterix
  • 6,005
  • 3
  • 17
  • 12
560
votes
17 answers

Why Choose Struct Over Class?

Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offering less functionality. Why choose it then?
bluedevil2k
  • 9,366
  • 8
  • 43
  • 57
560
votes
41 answers

Private properties in JavaScript ES6 classes

Is it possible to create private properties in ES6 classes? Here's an example. How can I prevent access to instance.property? class Something { constructor(){ this.property = "test"; } } var instance = new…
d13
  • 9,817
  • 12
  • 36
  • 44
557
votes
14 answers

How to read the value of a private field from a different class in Java?

I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. For example, why should I need to choose private field is it necessary? class IWasDesignedPoorly { private Hashtable…
Frank Krueger
  • 69,552
  • 46
  • 163
  • 208
544
votes
17 answers

ES6 class variable alternatives

Currently in ES5 many of us are using the following pattern in frameworks to create classes and class variables, which is comfy: // ES 5 FrameWork.Class({ variable: 'string', variable2: true, init: function(){ }, addItem:…
wintercounter
  • 7,500
  • 6
  • 32
  • 46
524
votes
11 answers

Static constant string (class member)

I'd like to have a private static constant for a class (in this case a shape-factory). I'd like to have something of the sort. class A { private: static const string RECTANGLE = "rectangle"; } Unfortunately I get all sorts of error from…
lb.
  • 5,666
  • 3
  • 17
  • 16
519
votes
11 answers

What is the difference between include and require in Ruby?

My question is similar to "What is the difference between include and extend in Ruby?". What's the difference between require and include in Ruby? If I just want to use the methods from a module in my class, should I require it or include it?
Owen
  • 22,247
  • 13
  • 42
  • 47
519
votes
18 answers

List attributes of an object

Is there a way to grab a list of attributes that exist on instances of a class? class new_class(): def __init__(self, number): self.multi = int(number) * 2 self.str = str(number) a = new_class(2) print(',…
MadSc13ntist
  • 19,820
  • 8
  • 25
  • 19
506
votes
7 answers

How to invoke the super constructor in Python?

class A: def __init__(self): print("world") class B(A): def __init__(self): print("hello") B() # output: hello In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in…
Mike
  • 58,961
  • 76
  • 175
  • 221