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
18
votes
4 answers

How to remove "__main__." from the beginning of user-created exception classes in Python

Is there a way to get a "prettier" exception rather than one prefaced with __main__MyExceptionTitle? Example: >>> class BadThings(Exception): ... def __init__(self, msg): ... self.msg = msg ... return ... >>> class…
narnie
  • 1,742
  • 1
  • 18
  • 34
18
votes
2 answers

class diagram viewer application for python3 source

Is there any application which can generate from python3 source something like the below link (i don't care about the representation rather the perfect content) http://www.codeproject.com/KB/IP/Searcharoo_3/ClassDiagram.png
vpas
  • 513
  • 1
  • 5
  • 18
18
votes
3 answers

Private class (not class method) in a Ruby module?

I'm new to Ruby (experienced with Python, C++ and C). I need to create a class that is only to be used by other classes and methods in a module. In Python, I'd just call it __classname. I'd use an empty typedef in C++. How do I do this in Ruby (or…
c4757p
  • 1,728
  • 4
  • 18
  • 25
18
votes
2 answers

What is the difference between Moq-ing a class or interface?

I've been using moq to mock objects in my unit tests and I've seen on the site about moq that it is able to mock both classes and interfaces. I had a discussion with one of my work mates the other day and they stated that there is never a reason to…
mezoid
  • 28,090
  • 37
  • 107
  • 148
18
votes
2 answers

pythonic class instance attribute calculated from other attributes

I have a class instance with attributes that are calculated from other attributes. The attributes will change throughout the life of the instance. All attributes are not necessarily defined when the object is initialized. what is the pythonic way…
twinturbotom
  • 1,504
  • 1
  • 21
  • 34
18
votes
2 answers

C# XML serialization of derived classes

Hi I am trying to serialize an array of objects which are derived from a class and I keep hitting the same error using c#. Any help is much appreciated. obviously this example has been scaled down for the purpose of this post in the real world Shape…
111111
  • 15,686
  • 6
  • 47
  • 62
18
votes
3 answers

Get Swift class name in "class func" method

I have a static method in Swift class BaseAsyncTask: WebServiceClient { class func execute(content : [String:AnyObject], cancelled:CustomBool) { // Print class name (BaseAsyncTask) here } } And I want to know how to…
Oscar Vasquez
  • 465
  • 2
  • 6
  • 14
18
votes
6 answers

What does "monolithic" mean?

I've seen it in the context of classes. I suspect it means that the class could use being broken down into logical subunits, but I can't find a good definition. Could you give some examples? Thanks for the help. Edit: I love the smart replies, but…
Kristian D'Amato
  • 3,996
  • 9
  • 45
  • 69
18
votes
2 answers

C++ declaring static enum vs enum in a class

What's the difference between the static enum and enum definitions when defined inside a class declaration like the one shown below? class Example { Example(); ~Example(); static enum Items{ desk = 0, chair, monitor }; enum…
user3731622
  • 4,844
  • 8
  • 45
  • 84
18
votes
1 answer

Friend class not working

I am getting the typical '... is private within this context' error. Can you tell me what I am doing wrong? Code is shortened for readability. in class SceneEditorWidgetController: (settingsdialog and the variable used here is defined in the…
RunOrVeith
  • 4,487
  • 4
  • 32
  • 50
18
votes
1 answer

(GCC bug?) Implicit conversion to a derived class

I've encountered a problem with implicit conversion in C++. The following is a minimal example: struct A { virtual void f()=0; // abstract }; struct Ad : A { virtual void f() {} // not abstract }; struct B { operator Ad () const { return…
Daniel Steck
  • 1,083
  • 10
  • 12
18
votes
9 answers

Ruby class instance variables and inheritance

I have a Ruby class called LibraryItem. I want to associate with every instance of this class an array of attributes. This array is long and looks something like ['title', 'authors', 'location', ...] Note that these attributes are not really…
rlandster
  • 7,294
  • 14
  • 58
  • 96
18
votes
4 answers

Setting a class attribute with a given name in python while defining the class

I am trying to do something like this: property = 'name' value = Thing() class A: setattr(A, property, value) other_thing = 'normal attribute' def __init__(self, etc) #etc.......... But I can't seem to find the reference to the class to…
prismofeverything
  • 8,799
  • 8
  • 38
  • 53
18
votes
6 answers

Is it possible to create a Windows Form in a C# Class Library?

I've been building DLL class libraries in C#, used as add-ons to an application which provides a Custom API. Up until now they've included mostly interfacing with databases, calculations, disk operations and so forth. I'm curious to know if I can…
Cody Zink
  • 189
  • 1
  • 1
  • 7
18
votes
2 answers

Having a "+" in the class name?

Class name: MyAssembly.MyClass+MyOtherClass The problem is obviously the + as separator, instead of traditionnal dot, its function, and to find official documentation to see if others separators exist.
Graveen
  • 404
  • 1
  • 5
  • 16