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
1 answer

Python Abstract class with concrete methods

I'm wondering if in python (3) an abstract class can have concrete methods. Although this seems to work I'm not sure this is the proper way to do this in python: from abc import ABCMeta, abstractclassmethod, abstractmethod class MyBaseClass: …
Leonardo
  • 4,046
  • 5
  • 44
  • 85
17
votes
2 answers

Scope of declared function within a function

I was wondering why php handles the scope of a declared function within a function differently when a function is declared inside a class function. For example: function test() // global function { function myTest() // global function. Why? { …
Codebeat
  • 6,501
  • 6
  • 57
  • 99
17
votes
5 answers

Private access in inheritance

class Person { public $name; private $age; //private access } class Employee extends Person{ public $id; public $salary; //class property } $emp = new Employee(); $emp->name="ABCD"; $emp->age =…
17
votes
11 answers

How many classes should a programmer put in one file?

In your object-oriented language, what guidelines do you follow for grouping classes into a single file? Do you always give each class a seperate file? Do you put tightly coupled classes together? Have you ever specified a couple of implementations…
Doug T.
  • 64,223
  • 27
  • 138
  • 202
17
votes
5 answers

Pickle a dynamically parameterized sub-class

I have a system which commonly stores pickled class types. I want to be able to save dynamically-parameterized classes in the same way, but I can't because I get a PicklingError on trying to pickle a class which is not globally found (not defined in…
Yonatan
  • 1,187
  • 15
  • 33
17
votes
2 answers

Constructors in Swift

I need some help in constructors in swift. I am sorry, if this question is incorrect or repeated, but I didn't found an answer to my question in another links. So, I have a class class myClass { override init(){ print("Hello World") …
Jack
  • 291
  • 2
  • 6
  • 12
17
votes
5 answers

Javascript recursion within a class

I am trying to get a recursion method to work in a class context. Within my class I have the following method: countChildren(n, levelWidth, level) { if (n.children && n.children.length > 0) { if (levelWidth.length <= level + 1) { …
David Montgomery
  • 473
  • 1
  • 4
  • 15
17
votes
1 answer

How to use self parameter, @staticmethod keyword inside a class and its methods

I have a python class which has multiple methods. I have defined my methods via @staticmethod instance and I want to call other methods of my class from inside my main function(main_function). I think I need self parameter for calling my other…
Stateless
  • 293
  • 2
  • 4
  • 18
17
votes
4 answers

How to access "__" (double underscore) variables in methods added to a class

Background I wish to use a meta class in order to add helper methods based on the original class. If the method I wish to add uses self.__attributeName I get an AttributeError (because of name mangling) but for an existing identical method this…
Haydon
  • 588
  • 1
  • 4
  • 13
17
votes
3 answers

PHP: How to Create Object Variables?

So for example I have this code: class Object{ public $tedi; public $bear; ...some other code ... } Now as you can see there are public variables inside this class. What I would like to do is to make these variables in a dynamic way,…
Adam Halasz
  • 57,421
  • 66
  • 149
  • 213
17
votes
2 answers

compiler error: is private within this context

I'm writing a class and when I compile, I get one error message that says, "is private within this context" and another that says, "invalid use of non-static data member". But if I comment out everything before the addShipment function in my cpp…
AdamK
  • 389
  • 1
  • 4
  • 12
17
votes
3 answers

Python - which is the better way of calling superclass' method?

All the while I have been using: SuperClass.__init__(self, *args, **kwargs) My reason is that this shows explicitly which superclass is used, especially in the case of multiple inheritance. However, other codes I came across use super(MyClass,…
kakarukeys
  • 21,481
  • 10
  • 35
  • 48
17
votes
2 answers

Constructor in PHP

Does a constructor method in PHP take the parameters declared in the class or not? I've seen on multiple sites and books and in the PHP documentation that the function function __construct() doesn't take any parameters.
Blueberry
  • 363
  • 1
  • 2
  • 10
17
votes
1 answer

Why aren't methods of an object created with class bound to it in ES6?

I like ES6 classes but I can't understand why I have to bind methods in the constructor: constructor() { this.someMethod = this.someMethod.bind(this) } I need to do this almost for any method. Is this a real limitation or am I missing…
ps-aux
  • 11,627
  • 25
  • 81
  • 128
17
votes
4 answers

Is there a Python shortcut for an __init__ that simply sets properties?

It's sometimes common in Python to see __init__ code like this: class SomeClass(object): def __init__(self, a, b, c, d, e, f, g): self.a = a self.b = b self.c = c self.d = d self.e = e self.f = f …
naiveai
  • 590
  • 2
  • 14
  • 42