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
17
votes
5 answers

How to conditionally add a function to a class template?

I have a Matrix class template as follows: template class Matrix { T data[nrows][ncols]; public: T& operator ()(std::size_t i, std::size_t j) { return data[i][j]; } }; What I…
user4085386
17
votes
3 answers

does order of members of objects of a class have any impact on performance?

May order of members in binary architecture of objects of a class somehow have an impact on performance of applications which use that class? and I'm wondering about how to decide order of members of PODs in case the answer is yes since programmer…
Pooria
  • 2,017
  • 1
  • 19
  • 37
17
votes
1 answer

How to properly overload the __add__ method?

I am required to write a class involving dates. I am supposed to overload the + operator to allow days being added to dates. To explain how it works: A Date object is represented as (2016, 4, 15) in the format (year, month, date). Adding integer 10…
Daniel Murphy
  • 330
  • 1
  • 2
  • 7
17
votes
2 answers

CKEditor add CSS styling to Preview and Editor

Is it possible to add CSS to style the Editor text as well as the Preview? The CMS has a different set of CSS files from the public part of the website and I want the editor to try (at least) and reflect the way it would look in the site. For…
Francisc
  • 77,430
  • 63
  • 180
  • 276
17
votes
8 answers

Accessing a protected member variable outside a class

I'm querying for the ID of a field by accessing a class function which someone has already put in place. The result is a object returned with protected member variables. I'm struggling to see how I can access the member variable values outside the…
user275074
17
votes
4 answers

Java: Convert Primitive Class

is there an easy in Java to convert primitive class objects into object class objects? Given a class Class cl, I want to convert it into a Class that has no primitives. Eg. Class cl = int.class; ... if (cl.isPrimitive()) { cl = Object of…
Max
  • 345
  • 1
  • 3
  • 10
17
votes
7 answers

How to create custom Divi module?

How can I add a custom module for Divi Wordpress theme? http://www.elegantthemes.com/gallery/divi/ Original modules are created in main-modules.php Example: class ET_Builder_Module_Gallery extends ET_Builder_Module { .... } But the…
Kiss Bálint
  • 217
  • 1
  • 3
  • 8
17
votes
3 answers

What does it mean to decorate a class or parameter?

What does it mean to Decorate or add an attribute to a class or parameter? What's the purpose and when would I do this? Links to resources and direct answers are welcome.
Mark G
  • 557
  • 1
  • 6
  • 17
17
votes
4 answers

Compare two instances of an object in Swift

Given the following class, how can all the values in two instances be compared to each other? // Client Object // class PLClient { var name = String() var id = String() var email = String() var mobile = String() var companyId =…
Michael Voccola
  • 1,827
  • 6
  • 20
  • 46
17
votes
9 answers

Why are NSRect, NSPoint, etc. structs, not classes?

I've recently needed to create my own type similar to NSRect that has an anchor point (essentially an NSRect with another NSPoint in it). After some research I found that I was actually probably better off to just make this a class (as in NSObject…
Oliver Cooper
  • 849
  • 7
  • 20
17
votes
1 answer

HTML5 & Bootstrap class="container", can it be applied to body or only div?

I keep bumping into this issue where everyone keeps: a) wanting to wrap HTML5 semantic tags with divs, and b) wants to apply class selectors to the divs and not the semantic tags. It's as if people are afraid of slapping classes onto semantic tags…
Padawan
  • 724
  • 1
  • 8
  • 20
17
votes
3 answers

In Java, the variable name can be same with the classname

In Java I can declare a variable, whose name is total same with its classname. I think it is a so confusing and strange design. So I have a problem in the code snippet below: how can the compiler distinguish the ClassName, it is referenced the…
Jimmy Zhang
  • 939
  • 1
  • 10
  • 15
17
votes
6 answers

Java: exception-throwing class?

I have classes DirReader and Search. The search uses DirReader. I want the search to know when DirReader throws exception. So how can I have class throwing exception? Currently, I use initCorrect -dummy var. Exception-style method may be more…
hhh
  • 50,788
  • 62
  • 179
  • 282
17
votes
2 answers

Create class diagram from already existent iphone code

does anybody know, how i could create automatically a UML class diagram from an already existent iphone project. Is it possible? Thanks in advance.
Simon D.
  • 525
  • 3
  • 6
  • 14
17
votes
3 answers

Android SDK error: Trying instantiate a class that is not a fragment

I am hardly trying to create a simple application with a top menu and a changeable view below (by pressing the buttons in the menu fragment we change the view of the fragment below). So, I have 2 fragments inside the main view but when trying to run…
ali
  • 10,927
  • 20
  • 89
  • 138
1 2 3
99
100