In computer programming, a class invariant is an invariant used to constrain objects of a class. Methods of the class should preserve the invariant. The class invariant constrains the state stored in the object. HTML and JavaScript in an IDE that uses color coding to highlight various keywords and help the developer see the function of each piece of code. ... Invariant may have meanings invariant (computer science), such as a combination of variables not altered in a loop invariant (mathematics), something unaltered by a transformation invariant (music) invariant (physics) conserved by system symmetry This is a disambiguation page — a navigational aid which lists other pages that might otherwise share the... In strictly mathematical branches of computer science the term object is used in a purely mathematical sense to refer to any thing. While this interpretation is useful in the discussion of abstract theory, it is not concrete enough to serve as a primitive datatype in the discussion of more concrete... In object-oriented programming, classes are used to group related variables and functions. ... method (from Greek methodos, met hodos literally way across). The word entered English in 1541 via French and Latin. ...
Class invariants are established during construction and constantly maintained between calls to public methods. Temporary breaking of class invariance between private method calls is possible, although not encouraged.
Example
This is an example of a class invariant in D. The invariant must hold to be true after the constructor is finished, before the destructor gets called, and at the entry and exit of all public member functions. D is an object-oriented, imperative systems programming language designed by Walter Bright of Digital Mars as a successor to C++. He has done this by adding some features and reducing the complexity of C++ syntax. ...
class Date { int day; int hour; invariant { assert(1 <= day && day <= 31); assert(0 <= hour && hour < 24); } this(int d, int h) { day = d; hour = h; } }
The invariant must hold to be true after the constructor is finished, before the destructor gets called, and at the entry and exit of all public member functions.
A class describes a collection of encapsulated instance variables and methods (functions), possibly with implementation of those types together with a constructor function that can be used to create objects of the class.
An invariant is what distinguishes datatypes and classes from each other, that is, a class does not allow use of all possible values for the state of the object, only those that are well-defined by the semantics of the intended use of the datatype.
Abstract classes are often used to represent abstract concepts or entities.