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
357
votes
12 answers

Java - get the current class name?

All I am trying to do is to get the current class name, and java appends a useless non-sense $1 to the end of my class name. How can I get rid of it and only return the actual class name? String className = this.getClass().getName();
aryaxt
  • 76,198
  • 92
  • 293
  • 442
348
votes
19 answers

What is the difference between private and protected members of C++ classes?

What is the difference between private and protected members in C++ classes? I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC…
Konrad
  • 39,751
  • 32
  • 78
  • 114
346
votes
2 answers

correct way to define class variables in Python

I noticed that in Python, people initialize their class attributes in two different ways. The first way is like this: class MyClass: __element1 = 123 __element2 = "this is Africa" def __init__(self): #pass or something else The other…
jeanc
  • 4,563
  • 4
  • 22
  • 27
321
votes
20 answers

Python function overloading

I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way. I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions…
Bullets
  • 3,251
  • 3
  • 15
  • 6
316
votes
6 answers

What is the difference between functions and classes to create reusable widgets?

I have realized that it is possible to create widgets using plain functions instead of subclassing StatelessWidget. An example would be this: Widget function({ String title, VoidCallback callback }) { return GestureDetector( onTap: callback, …
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
314
votes
3 answers

How to properly document S4 class slots using Roxygen2?

For documenting classes with roxygen(2), specifying a title and description/details appears to be the same as for functions, methods, data, etc. However, slots and inheritance are their own sort of animal. What is the best practice -- current or…
Paul 'Joey' McMurdie
  • 7,295
  • 5
  • 37
  • 41
314
votes
19 answers

Pointer to class data member "::*"

I came across this strange code snippet which compiles fine: class Car { public: int speed; }; int main() { int Car::*pSpeed = &Car::speed; return 0; } Why does C++ have this pointer to a non-static data member of a class? What is…
Ashwin Nanjappa
  • 76,204
  • 83
  • 211
  • 292
312
votes
15 answers

How do you create a static class in C++?

How do you create a static class in C++? I should be able to do something like: cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl; Assuming I created the BitParser class. What would the BitParser class definition look like?
andrewrk
  • 30,272
  • 27
  • 92
  • 113
312
votes
12 answers

difference between variables inside and outside of __init__() (class and instance attributes)

Is there any difference at all between these classes besides the name? class WithClass (): def __init__(self): self.value = "Bob" def my_func(self): print(self.value) class WithoutClass (): value = "Bob" def…
Teifion
  • 108,121
  • 75
  • 161
  • 195
307
votes
21 answers

How do I remove code duplication between similar const and non-const member functions?

Let's say I have the following class X where I want to return access to an internal member: class Z { // details }; class X { std::vector vecZ; public: Z& Z(size_t index) { // massive amounts of code for validating…
Kevin
  • 25,207
  • 17
  • 54
  • 57
302
votes
35 answers

Find a class somewhere inside dozens of JAR files?

How would you find a particular class name inside lots of jar files? (Looking for the actual class name, not the classes that reference it.)
Kapsh
  • 20,751
  • 13
  • 36
  • 44
300
votes
11 answers

What is the difference between Integer and int in Java?

For example why can you do: int n = 9; But not: Integer n = 9; And you can do: Integer.parseInt("1"); But not: int.parseInt("1");
mino
  • 6,978
  • 21
  • 62
  • 75
299
votes
11 answers

How to use Class in Java?

There's a good discussion of Generics and what they really do behind the scenes over at this question, so we all know that Vector is a vector of integer arrays, and HashTable is a table of whose keys are strings and values…
Karl
  • 8,967
  • 5
  • 29
  • 31
297
votes
6 answers

Possibilities for Python classes organized across files?

I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.
brianegge
  • 29,240
  • 13
  • 74
  • 99
290
votes
9 answers

Java: Multiple class declarations in one file

In Java, you can define multiple top level classes in a single file, providing that at most one of these is public (see JLS §7.6). See below for example. Is there a tidy name for this technique (analogous to inner, nested, anonymous)? The JLS says…
Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49