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

When do I need to declare my own destructor?

class Point { public: float x,y; Point() {} Point(float,float); Point operator + (Point); Point operator * (double); void rotate_p(float); void render_p(Point*); void sub(float); float…
0ctoDragon
  • 541
  • 1
  • 7
  • 20
18
votes
9 answers

Creating variable of type to store object in C#

I'm somewhat new to programming and I have a question about classes, inheritance, and polymorphism in C#. While learning about these topics, occasionally I'll come across code that looks something like this: Animal fluffy = new Cat(); // where…
dhughes01
  • 205
  • 1
  • 2
  • 3
18
votes
4 answers

WooCommerce - change order status with php code

I am trying to change order status in WooCommerce, but I encountered no luck so far. $order instance is created successfully (I know it because echo $order->status; works fine, $order_id is also correct. $order->status = 'pending'; simply doesn't…
NakedCat
  • 852
  • 1
  • 11
  • 40
18
votes
4 answers

SRC folder in Eclipse is empty (MainActivity class not created) after creating a new android project using Eclipse

SRC folder in Eclipse is empty (MainActivity class not created) after creating a new android project using Eclipse- I created a new android project using Eclipse. But I am seeing SRC folder is empty in the project explorer. But as per my…
subin
  • 191
  • 1
  • 1
  • 4
18
votes
9 answers

find all classes and interfaces a class extends or implements recursively

I was wondering if there was an easy way of determining the complete list of Types that a Java class extends or implements recursively? for instance: class Foo extends Bar implements I1, I2 {...} class Bar implements I3 {...} interface I1 extends…
coderatchet
  • 8,120
  • 17
  • 69
  • 125
18
votes
1 answer

create a new class using a string name in typescript

I am writing an XML loader/parser (and new to typescript), I can load the XML fine, however I'm trying to dynamically parse the XML data back into a class/object. The problem is, I would like to create a class using a string variable; ie var…
user3171294
  • 181
  • 1
  • 1
  • 3
18
votes
1 answer

Where does getResourceAsStream(file) search for the file?

I've got confused by getResourceAsStream(); My package structure looks like: \src |__ net.floodlightcontroller // invoked getResourceAsStream() here |__ ... |__ resources |__ floodlightdefault.properties //target |__ ... And I want to read…
qweruiop
  • 3,156
  • 6
  • 31
  • 55
18
votes
2 answers

Iterate over each sibling element

Context: I'm building a form and script which will perform an ajax query, based on clicking a specific button. There are multiple div blocks with elements of the same class, and based on the div block in which, a button is clicked, different forms…
Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86
18
votes
1 answer

PHP - extend method like extending a class

I have 2 class: class animal{ public function walk(){ walk; } } class human extends animal{ public function walk(){ with2legs; } } This way, if i call human->walk(), it only runs with2legs; But I want the run the…
Tony
  • 425
  • 1
  • 5
  • 12
18
votes
8 answers

Creating the instance of abstract class or anonymous class

In this code here is it creating the object of abstract class or anonymous class? Please tell me. I am little bit confused here. public abstract class AbstractDemo { abstract void showMessage(); abstract int add(int x,int y); public…
DroidNinja
  • 997
  • 1
  • 8
  • 9
18
votes
8 answers

Accessing Method from other Classes Objective-C

Looked for an answer for this question, but I haven't found a suitable one yet. I'm hoping you guys (and gals) can help me out! (This is for an iPhone app) Alright, I have a Mutliview application. Each view has it's own class, and everything is…
Ethan Mick
  • 9,517
  • 14
  • 58
  • 74
18
votes
8 answers

What is the 'this' pointer?

I'm fairly new to C++, and I don't understand what the this pointer does in the following scenario: void do_something_to_a_foo(Foo *foo_instance); void Foo::DoSomething() { do_something_to_a_foo(this); } I grabbed that from someone else's post…
user2371809
  • 351
  • 2
  • 4
  • 9
18
votes
4 answers

How to write hashCode method for a particular class?

I'm trying to generate a hashCode() method for my simple class but i'm not getting anywhere with it. I would appreciate any help. I've implemented the equals() method, which looks as follows, and would also like to know if I need to implement…
A Gore
  • 1,870
  • 2
  • 15
  • 26
18
votes
6 answers

Declare static member variables like Java's in Objective-C

How can I make an Objective-C class with class-level variables like this Java class? public class test { public static final String tableName = "asdfas"; public static final String id_Column = "_id"; public static final String…
Awais Tariq
  • 7,724
  • 5
  • 31
  • 54
18
votes
3 answers

how do I add a final variable to class diagram

I am designing a class diagram for scrabble game. In one of the classes, I have final variable declared. Can anybody tell me, how can I indicate a variable as final in the UML class diagram?
Noopur Phalak
  • 313
  • 1
  • 2
  • 6