Questions tagged [class]

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

Not to be confused with CSS classes. Use 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:

71255 questions
2768
votes
7 answers

Understanding Python super() with __init__() methods

I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine. I'm curious to know about the actual difference between the following 2 child classes. class Base(object): def __init__(self): …
Mizipzor
  • 45,705
  • 20
  • 92
  • 136
2140
votes
23 answers

Are static class variables possible in Python?

Is it possible to have static class variables or methods in Python? What syntax is required to do this?
Andrew Walker
  • 36,318
  • 7
  • 54
  • 80
2091
votes
23 answers

When to use self over $this?

In PHP 5, what is the difference between using self and $this? When is each appropriate?
Casey Watson
  • 46,980
  • 10
  • 30
  • 30
1561
votes
56 answers

What does "Could not find or load main class" mean?

A common problem that new Java developers experience is that their programs fail to run with the error message: Could not find or load main class ... What does this mean, what causes it, and how should you fix it?
Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
1425
votes
6 answers

Why do Python classes inherit object?

Is there any reason for a class declaration to inherit from object? I just found some code that does this and I can't find a good reason why. class MyClass(object): # class code follows...
tjvr
  • 15,039
  • 6
  • 21
  • 26
1196
votes
26 answers

What is the purpose of the word 'self'?

What is the purpose of the self word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this: class…
richzilla
  • 34,719
  • 13
  • 51
  • 80
1084
votes
26 answers

When should you use a class vs a struct in C++?

In what scenarios is it better to use a struct vs a class in C++?
Alan Hinchcliffe
  • 11,094
  • 3
  • 16
  • 11
1045
votes
8 answers

What is the difference between old style and new style classes in Python?

What is the difference between old style and new style classes in Python? When should I use one or the other?
readonly
  • 306,152
  • 101
  • 198
  • 201
768
votes
19 answers

What's the difference between struct and class in .NET?

What's the difference between struct and class in .NET?
Keith
  • 133,927
  • 68
  • 273
  • 391
691
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
  • 17,557
  • 13
  • 57
  • 68
681
votes
15 answers

How do I call a parent class's method from a child class in Python?

When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: package Foo; sub frotz { …
jjohn
  • 8,570
  • 4
  • 20
  • 21
677
votes
13 answers

Difference between object and class in Scala

I'm just going over some Scala tutorials on the Internet and have noticed in some examples an object is declared at the start of the example. What is the difference between class and object in Scala?
Steve
  • 19,541
  • 21
  • 63
  • 90
653
votes
13 answers

What is the difference between __init__ and __call__?

I want to know the difference between __init__ and __call__ methods. For example: class test: def __init__(self): self.a = 10 def __call__(self): b = 20
sam
  • 15,535
  • 21
  • 72
  • 109
644
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
  • 9,713
  • 8
  • 29
  • 31
644
votes
12 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
  • 27,174
  • 47
  • 133
  • 181
1
2 3
99 100