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
492
votes
29 answers

What are the differences between struct and class in C++?

This question was already asked in the context of C#/.Net. Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design. I'll start…
palm3D
  • 7,970
  • 6
  • 28
  • 33
483
votes
36 answers

Use of .apply() with 'new' operator. Is this possible?

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible? What I want to do is something like this (but the code below does not work): function…
Prem
  • 15,911
  • 11
  • 31
  • 35
479
votes
8 answers

Static vs class functions/variables in Swift classes?

The following code compiles in Swift 1.2: class myClass { static func myMethod1() { } class func myMethod2() { } static var myVar1 = "" } func doSomething() { myClass.myMethod1() myClass.myMethod2() myClass.myVar1 =…
Senseful
  • 86,719
  • 67
  • 308
  • 465
462
votes
9 answers

Difference between a class and a module

I came from Java, and now I am working more with Ruby. One language feature I am not familiar with is the module. I am wondering what exactly is a module and when do you use one, and why use a module over a class?
Josh Moore
  • 13,338
  • 15
  • 58
  • 74
454
votes
13 answers

Is it possible to make abstract classes in Python?

How can I make a class or method abstract in Python? I tried redefining __new__() like so: class F: def __new__(cls): raise Exception("Unable to create an instance of abstract class %s" %cls) But now, if I create a class G that inherits…
user1632861
443
votes
4 answers

What are data classes and how are they different from common classes?

With PEP 557 data classes are introduced into python standard library. They make use of the @dataclass decorator and they are supposed to be "mutable namedtuples with default" but I'm not really sure I understand what this actually means and how…
kingJulian
  • 5,601
  • 5
  • 17
  • 30
435
votes
2 answers

Java Generics With a Class & an Interface - Together

I want to have a Class object, but I want to force whatever class it represents to extend class A and implement interface B. I can do: Class Or: Class but I can't do both. Is there a way to do this?
Alex Beardsley
  • 20,988
  • 15
  • 52
  • 67
433
votes
9 answers

What is the difference between static func and class func in Swift?

I can see these definitions in the Swift library: extension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) -> Bool } protocol BooleanLiteralConvertible { typealias BooleanLiteralType class func…
Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
421
votes
19 answers

How can I create an object and add attributes to it?

I want to create a dynamic object (inside another object) in Python and then add attributes to it. I tried: obj = someobject obj.a = object() setattr(obj.a, 'somefield', 'somevalue') but this didn't work. Any ideas? edit: I am setting the…
John
  • 21,047
  • 43
  • 114
  • 155
417
votes
7 answers

Difference between 'cls' and 'self' in Python classes?

Why is cls sometimes used instead of self as an argument in Python classes? For example: class Person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname @classmethod def…
Scaraffe
  • 5,041
  • 5
  • 21
  • 20
406
votes
14 answers

Public Fields versus Automatic Properties

We're often told we should protect encapsulation by making getter and setter methods (properties in C#) for class fields, instead of exposing the fields to the outside world. But there are many times when a field is just there to hold a value and…
I. J. Kennedy
  • 24,725
  • 16
  • 62
  • 87
404
votes
20 answers

Declaring static constants in ES6 classes?

I want to implement constants in a class, because that's where it makes sense to locate them in the code. So far, I have been implementing the following workaround with static methods: class MyClass { static constant1() { return 33; } static…
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
394
votes
3 answers

How can I call a function within a class?

I have this code which calculates the distance between two coordinates. The two functions are both within the same class. However, how do I call the function distToPoint in the function isNear? class Coordinates: def distToPoint(self, p): …
Steven
  • 4,193
  • 3
  • 17
  • 11
360
votes
21 answers

How do you make a deep copy of an object?

It's a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?
Andrei Savu
  • 8,525
  • 7
  • 46
  • 53
360
votes
9 answers

Using two CSS classes on one element

What am I doing wrong here? I have a .social div, but on the first one I want zero padding on the top, and on the second one I want no bottom border. I have attempted to create classes for this first and last but I think I've got it wrong…
Francesca
  • 26,842
  • 28
  • 90
  • 153