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
3 answers

Why can't static classes have non-static methods and variables?

Why can't static classes have non-static methods and variables when non-static classes can have static methods and variables? What is the advantage of having static methods and variables in a non static class? Though having a static constructor in a…
Simsons
  • 12,295
  • 42
  • 153
  • 269
17
votes
5 answers

python: immutable private class variables?

Is there any way to translate this Java code into Python? class Foo { final static private List thingies = ImmutableList.of(thing1, thing2, thing3); } e.g. thingies is an immutable private list of Thingy objects that belongs to…
Jason S
  • 184,598
  • 164
  • 608
  • 970
17
votes
9 answers

Class attribute declaration: private vs public

What are the advantages of defining a private attribute instead of a public attribute? Why should I have the extra work of creating methods to access and modify privates attributes if I can just make them public?
brsunli
  • 285
  • 1
  • 4
  • 10
17
votes
7 answers

When is it the right time to use C# class library (.dll)?

I'm a programmer who has never really used .dll files. Of cause, when I need 3rd party software, such as a graphics library, a library to help me create graphs etc. I do add the references/ddl files to my program and use them in my code. Also, it…
CasperT
  • 3,425
  • 11
  • 41
  • 56
17
votes
6 answers

What is the purpose of accessors?

Can somebody help me understand the get & set? Why are they needed? I can just make a public variable.
MasterMastic
  • 20,711
  • 12
  • 68
  • 90
17
votes
6 answers

Why use classes instead of functions?

I do know some advantages to classes such as variable and function scopes, but other than that is just seems easier to me to have groups of functions rather than to have many instances and abstractions of classes. So why is the "norm" to group…
sdfadfaasd
  • 1,446
  • 2
  • 16
  • 18
17
votes
2 answers

C++: any way to prevent any instantiation of an abstract base class?

Aside from having a pure virtual function, is there a way to prevent an instantiation of an abstract base class? I can do this: class BaseFoo { virtual void blah() = 0; }; class Foo : public BaseFoo { virtual void blah() {} }; but I'd like…
Jason S
  • 184,598
  • 164
  • 608
  • 970
17
votes
5 answers

How can I transform a Map to a case class in Scala?

If I have a Map[String,String]("url" -> "xxx", "title" -> "yyy"), is there an way to generically transform it into a case class Image(url:String, title:String)? I can write a helper: object Image{ def fromMap(params:Map[String,String]) =…
tommy chheng
  • 9,108
  • 9
  • 55
  • 72
17
votes
4 answers

How much info should I put into a class? (OOP)

I'm a 1st level C# programming student, though I've been dabbling in programming for a few years, and learning above and beyond what the class teaches me is just what I'm doing so that I'm thoroughly prepared once I get out into the job environment.…
Tyler W
  • 472
  • 1
  • 6
  • 21
17
votes
2 answers

Kotlin variable initialization for child class behaves weird for initializing variable with value 0

I have created the following class hierarchy: open class A { init { f() } open fun f() { println("In A f") } } class B : A() { var x: Int = 33 init { println("x: " + x) } override fun f()…
17
votes
2 answers

Flutter, Dart. Create anonymous class

Maybe it's really dumb question. But I cannot believe there is no resources, where it's described. Even from the official documentation. What I'm trying to do, it's create Anonymous class for the next function. How to create Anonymous class in…
GensaGames
  • 5,538
  • 4
  • 24
  • 53
17
votes
3 answers

VBA - Returning array from Property Get

If arrays are returned by reference, why doesn't the following work: 'Class1 class module Private v() As Double Public Property Get Vec() As Double() Vec = v() End Property Private Sub Class_Initialize() ReDim v(0 To 3) End Sub ' end class…
ThomasMcLeod
  • 7,603
  • 4
  • 42
  • 80
17
votes
1 answer

Python - how to pass to a function argument type of a class object (typing)

I suppose that came with python 3.7 (not sure), the possibility to pass to a function not only the variable name but also the type of the variable. What I would like to know is if there is any possibility of passing the type of a particular…
17
votes
6 answers

c++ abstract base class private members

Just wanted some clarification. Should abstract base classes never have private members? For example class abc{ public: virtual void foo()=0; private: int myInt; } you can never access myInt since you cannot create an instance of abc and it…
valmo
  • 1,156
  • 2
  • 12
  • 22
17
votes
3 answers

"Class of where T : Enum" not working

Possible Duplicate: Create Generic method constraining T to an Enum Is there any reason why we can't do this in C#? And, if possible, how can I do something similar! What I want : public class ATag where T : enum { [Some code…
Simon Dugré
  • 17,980
  • 11
  • 57
  • 73