Instance variable

Last updated

In class-based, object-oriented programming, an instance variable is a variable defined in a class (i.e., a member variable), for which each instantiated object of the class has a separate copy, or instance [1] [2] . An instance variable has similarities with a class variable, [3] but is non-static. An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class. Access modifiers can be given to the instance variable.

Contents

An instance variable is not a class variable [4] , although there are similarities. Both are a type of class attribute (or class property, field, or data member). While an instance variable's value may differ between instances of a class, a class variable can only have one value at any one time, shared between all instances. The same dichotomy between instance and class members applies to methods ("member functions") as well.

Each instance variable lives in memory for the lifetime of the object it is owned by. [5]

Instance variables are properties of that object. All instances of a class have their own copies of instance variables, even if the value is the same from one object to another. One class instance can change values of its instance variables without affecting all other instances. A class may have both instance variables and class variables.

Instance variables can be used by all instance methods of an object, but may not be used by class methods. An instance variable may also be changed directly, provided access restrictions are set. [6]

Example

C++

structRequest{staticintcount1;// variable name is not importantintnumber;Request();{number=count1;// modifies the instance variable "this->number"++count1;// modifies the class variable "Request::count1"}};intRequest::count1=0;

In this C++ example, the instance variable Request::number is a copy of the class variable Request::count1 where each instance constructed is assigned a sequential value of count1 before it is incremented. Since number is an instance variable, each Request object contains its own distinct value; in contrast, there is only one object Request::count1 available to all class instances with the same value.

Java

//Example.javaclassExample{publicintx=0;publicvoidsetX(intnewValue){this.x=newValue;}}//Main.javaclassMain{publicstaticvoidmain(String[]args){Exampleexample1=newExample();Exampleexample2=newExample();//We can set the value of x by itself, as the variable is publicexample1.x=10;assertexample1.x==10;assertexample2.x==0;//As setX is an instance method, it can also access the variableexample2.setX(-10);assertexample1.x==10;assertexample2.x==-10;}}

In this Java example, we can see how instance variables can be modified in one instance without affecting another.

Python

classDog:def__init__(self,breed):self.breed=breed# instance variable# dog_1 is an object# which is also an instance of the Dog classdog_1=Dog("Border Collie")

In the above Python code, the instance variable is created when an argument is parsed into the instance, with the specification of the breed positional argument.

Related Research Articles

In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state and implementations of behavior.

<span class="mw-page-title-main">Singleton pattern</span> Design pattern in object-oriented software development

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. One of the well-known "Gang of Four" design patterns, which describes how to solve recurring problems in object-oriented software, the pattern is useful when exactly one object is needed to coordinate actions across a system.

In class-based, object-oriented programming, a class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist.

In object-oriented (OO) and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created. In some cases, an object is considered immutable even if some internally used attributes change, but the object's state appears unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.

A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of state data and behavior; these compose an interface, which specifies how the object may be used. A method is a behavior of an object parametrized by a user.

In object-oriented programming (OOP), the object lifetime of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementations of a given language, and lifetime of a particular object may vary from one run of the program to another.

In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.

This article compares two programming languages: C# with Java. While the focus of this article is mainly the languages and their features, such a comparison will necessarily also consider some features of platforms and libraries. For a more detailed comparison of the platforms, see Comparison of the Java and .NET platforms.

In class-based, object-oriented programming, a constructor is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.

<span class="mw-page-title-main">Java syntax</span> Set of rules defining correctly structured program

The syntax of Java is the set of rules defining how a Java program is written and interpreted.

In object-oriented programming, a member variable is a variable that is associated with a specific object, and accessible for all its methods.

In object-oriented programming (OOP), an inner class or nested class is a class declared entirely within the body of another class or interface. It is distinguished from a subclass.

In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once.

In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; by contrast, a concrete typecan be instantiated directly. Instantiation of an abstract type can occur only indirectly, via a concrete subtype.

In computer programming, a declaration is a language construct specifying identifier properties: it declares a word's (identifier's) meaning. Declarations are most commonly used for functions, variables, constants, and classes, but can also be used for other entities such as enumerations and type definitions. Beyond the name and the kind of entity, declarations typically specify the data type, or the type signature ; types may also include dimensions, such as for arrays. A declaration is used to announce the existence of the entity to the compiler; this is important in those strongly typed languages that require functions, variables, and constants, and their types to be specified with a declaration before use, and is used in forward declaration. The term "declaration" is frequently contrasted with the term "definition", but meaning and usage varies significantly between languages; see below.

C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The aspect compile-time type safety was not fully achieved, since it was shown in 2016 that it is not guaranteed in all cases.

In computer programming, a constant is a value that is not altered by the program during normal execution. When associated with an identifier, a constant is said to be "named," although the terms "constant" and "named constant" are often used interchangeably. This is contrasted with a variable, which is an identifier with a value that can be changed during normal execution. To simplify, constants' values remains, while the values of variables varies, both hence their names.

References

  1. "Instance Variables in C++ Programming". Dremendo. Retrieved 2024-03-08.
  2. "Java Variables". GeeksforGeeks. 2017-02-06. Retrieved 2024-03-08.
  3. "The Java Tutorial, Variables". docs.oracle.com. Oracle. Archived from the original on 23 October 2014. Retrieved 23 October 2014.
  4. "Difference between Instance Variable and Class Variable". GeeksforGeeks. 2021-04-26. Retrieved 2024-03-08.
  5. "The Java Tutorials, Understanding Class Members". docs.oracle.com. Oracle. Archived from the original on 11 October 2014. Retrieved 23 October 2014.
  6. Matuszek, David. "Static". cis.upenn.edu. University of Pennsylvania. Archived from the original on 23 October 2014. Retrieved 23 October 2014.