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

C++ typedef class use

Why use a typedef class {} Name ? I learnt this in IBM C++ doc, no hint to use here.
kiriloff
  • 25,609
  • 37
  • 148
  • 229
18
votes
3 answers

C++ calling a function from a vector of function pointers inside a class where the function definition is in main

Alright, in my main i have: void somefunction(); int main() { //bla bla bla SomeClass myclass = SomeClass(); void(*pointerfunc)() = somefunction; myclass.addThingy(pointerfunc); //then later i do …
Steven Venham
  • 600
  • 1
  • 3
  • 18
18
votes
7 answers

Immutable objects in PHP?

Is it a good idea to create objects that cannot be changed in PHP? For example a date object which has setter methods, but they will always return a new instance of the object (with the modified date). Would these objects be confusing to other…
Elfy
  • 1,733
  • 6
  • 19
  • 39
18
votes
5 answers

Custom Java classloader not being used to load dependencies?

I've been trying to set up a custom classloader that intercepts classes to print out which classes are being loaded into the application. The classloader looks like this public class MyClassLoader extends ClassLoader { @Override public…
Li Haoyi
  • 15,330
  • 17
  • 80
  • 137
18
votes
7 answers

PHP class constructor in interface or class

I'm having some issues thinking out a good structure to build my classes and objects. In the code below I make use of an interface to define my class methods, but I also want to pass a database connection to my constructor so the class had this…
randomizer
  • 1,619
  • 3
  • 15
  • 31
18
votes
9 answers

Should constructors accept parameters or should I create setters?

I have two options. Either make a class that accepts a lot arguments in its constructors, or create a lot of setter methods and an init method. I'm not sure which is preferred option, should some arguments be accepted in constructors, while others…
corazza
  • 31,222
  • 37
  • 115
  • 186
18
votes
2 answers

Derived class defined later in the same file "does not exist"?

Let’s suppose we’ve got two php files, a.php and b.php Here’s content of file a.php:
Michele Locati
  • 1,655
  • 19
  • 25
18
votes
2 answers

Decorators and class method

I am having trouble understanding why the following happens. I am having a decorator which does nothing except it checks whether a function is a method. I thought I have understood what method in Python is, but obviously, this is not the…
Joe M.
  • 609
  • 3
  • 11
18
votes
2 answers

How to get the current class name at runtime?

I'm trying to get a current class name into a string. For example: public class Marker : Mark { string currentclass = ???; } public abstract class MiniMarker : Mark { } I'd like to get the string from Marker class so I do not have to put it…
Craig
  • 195
  • 1
  • 1
  • 5
18
votes
2 answers

Get only first class of an HTML element

I'm using the event.target.className to get the ClassName, but sometimes an element has multiple class names, how can I make it, so it only gives the first class name as outcome? Oh, and please without jQuery.
user1544892
17
votes
1 answer

How do you declare a type alias in a scala constructor?

If I have a class that takes a tuple in its constructor among other values such as: class Foo(a: Int, b: String, c: (Int, String)) How do I use an abstract type to give the tuple a more descriptive name in a lightweight fashion (without wrapping…
Matthew Pickering
  • 523
  • 1
  • 5
  • 16
17
votes
2 answers

Specializing a template class as a struct

I was just over specializing std::hash for a user-defined type using: template<> struct hash<...> {...}; When VC10 greeted me with the warning: warning C4099: 'std::hash<_Kty>': type name first seen using 'class' now seen using 'struct' and I…
Christian Rau
  • 45,360
  • 10
  • 108
  • 185
17
votes
4 answers

error C2512: no appropriate default constructor available

I am getting this annoying error and I don't know why =( ! This is the question , I solved it but I am having a problem with the constructor. Write a program that defines a class called Circle that includes radius (type double) as data members.…
user1092492
  • 181
  • 1
  • 2
  • 5
17
votes
5 answers

What determines when a class object is destroyed in PHP?

Let's say that we have class CFoo. In the following example when is CFoo::__destruct() called? function MyPHPFunc() { $foo = new CFoo(); . . . // When/where/how does $foo get destroyed/deleted? } In this example would the destructor be…
Jim Fell
  • 13,750
  • 36
  • 127
  • 202
17
votes
5 answers

getter and setter for class in class c#

Assuming we have a class InnerClass with attributes and getter/setter. We also have a class OuterClass containing the InnerClass. e.g. class InnerClass { private int m_a; private int m_b; public int M_A { get { …
DummyCSharp